Arrays in Wolfram Language

In Wolfram Language, an array is represented by a List. Lists are much more flexible and powerful than arrays in many other languages, as they can contain elements of different types and can be nested to create multi-dimensional structures.

(* Here we create a list a that will hold exactly 5 integers. *)
a = ConstantArray[0, 5];
Print["emp: ", a]

(* We can set a value at an index using Part (or [[]]). Note that Wolfram Language uses 1-based indexing. *)
a[[5]] = 100;
Print["set: ", a]
Print["get: ", a[[5]]]

(* The Length function returns the length of a list. *)
Print["len: ", Length[a]]

(* Use this syntax to declare and initialize a list in one line. *)
b = {1, 2, 3, 4, 5};
Print["dcl: ", b]

(* In Wolfram Language, you don't need to specify the length when initializing a list. *)
b = {1, 2, 3, 4, 5};
Print["dcl: ", b]

(* You can use PadRight to create a list with specific elements at specific positions. *)
b = PadRight[{100}, 5, {0, 0, 400, 500}];
Print["idx: ", b]

(* To create multi-dimensional data structures, you can nest lists. *)
twoD = ConstantArray[0, {2, 3}];
Do[
  Do[
    twoD[[i, j]] = i + j - 2,
    {j, 1, 3}
  ],
  {i, 1, 2}
];
Print["2d: ", twoD]

(* You can create and initialize multi-dimensional lists at once too. *)
twoD = {{1, 2, 3}, {1, 2, 3}};
Print["2d: ", twoD]

When you run this code in a Wolfram Language environment (like Mathematica or Wolfram Desktop), you’ll see output similar to this:

emp: {0, 0, 0, 0, 0}
set: {0, 0, 0, 0, 100}
get: 100
len: 5
dcl: {1, 2, 3, 4, 5}
dcl: {1, 2, 3, 4, 5}
idx: {100, 0, 0, 400, 500}
2d: {{0, 1, 2}, {1, 2, 3}}
2d: {{1, 2, 3}, {1, 2, 3}}

Note that in Wolfram Language, lists (which are used like arrays in many other languages) are printed with curly braces {} instead of square brackets [].

Wolfram Language’s lists are more flexible than traditional arrays. They can be easily resized, can contain elements of different types, and provide a wide range of built-in functions for manipulation and analysis. This makes them a powerful tool for various computational tasks.