Slices in Wolfram Language

(* Slices are an important data type in Wolfram Language, giving
   a more powerful interface to sequences than traditional lists. *)

(* Unlike lists, slices in Wolfram Language are created using the 
   Range function or by taking parts of existing lists. An empty
   slice is represented by an empty list. *)

s = {}
Print["uninit: ", s, " ", s === {}, " ", Length[s] == 0]

(* To create an empty slice with non-zero length, we can use 
   ConstantArray. Here we make a list of empty strings of length 3. *)

s = ConstantArray["", 3]
Print["emp: ", s, " len: ", Length[s]]

(* We can set and get just like with lists. *)

s[[1]] = "a"
s[[2]] = "b"
s[[3]] = "c"
Print["set: ", s]
Print["get: ", s[[3]]]

(* Length returns the length of the slice as expected. *)

Print["len: ", Length[s]]

(* In addition to these basic operations, slices support several 
   more that make them richer than traditional lists. One is 
   AppendTo, which adds one or more new values to the end. *)

s = AppendTo[s, "d"]
s = Join[s, {"e", "f"}]
Print["apd: ", s]

(* Slices can also be copied. Here we create a new list c 
   with the same elements as s. *)

c = s
Print["cpy: ", c]

(* Slices support a "part" operator with the syntax 
   slice[[start;;end]]. For example, this gets a slice
   of the elements s[[3]], s[[4]], and s[[5]]. *)

l = s[[3;;5]]
Print["sl1: ", l]

(* This slices up to (but excluding) s[[6]]. *)

l = s[[;;5]]
Print["sl2: ", l]

(* And this slices from (and including) s[[3]] to the end. *)

l = s[[3;;]]
Print["sl3: ", l]

(* We can declare and initialize a variable for slice
   in a single line as well. *)

t = {"g", "h", "i"}
Print["dcl: ", t]

(* Wolfram Language has built-in functions for comparing lists. *)

t2 = {"g", "h", "i"}
If[t === t2,
  Print["t == t2"]
]

(* Lists can be composed into multi-dimensional data
   structures. The length of the inner lists can
   vary, unlike with multi-dimensional arrays. *)

twoD = Table[
  Table[i + j, {j, 1, i + 1}],
  {i, 0, 2}
]
Print["2d: ", twoD]

(* Executing the program *)

uninit: {} True True
emp: {"", "", ""} len: 3
set: {"a", "b", "c"}
get: c
len: 3
apd: {"a", "b", "c", "d", "e", "f"}
cpy: {"a", "b", "c", "d", "e", "f"}
sl1: {"c", "d", "e"}
sl2: {"a", "b", "c", "d", "e"}
sl3: {"c", "d", "e", "f"}
dcl: {"g", "h", "i"}
t == t2
2d: {{0}, {1, 2}, {2, 3, 4}}

Note that while slices in Wolfram Language are similar to those in other languages, they are typically implemented as lists. The Wolfram Language provides a rich set of built-in functions for manipulating these list structures, making them very versatile and powerful.

Now that we’ve seen lists and parts of lists (which are similar to slices in other languages), we’ll look at Wolfram Language’s other key built-in data structure: associations.