WolframLang: Get Parts of List

By Xah Lee. Date: . Last updated: .

There are many functions that extract sub-expression by position:

Get Parts by Index

Part[expr, i]

🔸 SHORT SYNTAX: expr[[i]]

ith part of expr. If i is negative, count from right.

Part

x = {a, b, c, {d1, d2}, e};
Part[x, 2] === b

(* short syntax *)
x[[2]] === b

(* count from right *)
x[[-2]] === {d1, d2}
Part[expr, {a, b, c}]

🔸 SHORT SYNTAX: expr[[{a, b, c}]]

Same as { Part[expr, a], Part[expr, b], Part[expr, c] }

x = {a, b, c, {d1, d2}, e};
x[[{2,-1}]] === {b, e}
Part[expr, a, b, c]

🔸 SHORT SYNTAX: expr[[a, b, c]]

same as Part[Part[Part[expr, a], b], c]

x = {a, b, c, {d1, d2}, e};
x[[4,1]] === d1
Part[expr, m;;n]

🔸 SHORT SYNTAX: expr[[m;;n]]

(note: a;;b is short for Span[a, b])

parts m through n. If m is omitted, default to beginning. If n is omitted, default to end.

x = {a, b, c, {d1, d2}, e};
x[[2;;4]] === {b, c, {d1, d2}}
  • expr[[m;;]] → part m to end
  • expr[[;;n]] → beginning to n
  • expr[[;;,j]] → column j
  • expr[[m1;;n1, m2;;n2]] → submatrix
(* column 1 *)
{{a,b}, {c,d}}[[;;,1]] === {a, c}

Get Element by Position: Extract

Extract
  • Extract[expr, position]
  • Extract[expr, {pos1, pos2, etc}]

return the part of expr at a given Position, or a list of them.

Extract

💡 TIP: this is most useful to pick one node in a tree, or pick several.

xx = {a, {{b,c}, d}, e};

Extract[ xx, {1} ] === a
Extract[ xx, {2} ] === {{b, c}, d}
Extract[ xx, {3} ] === e
Extract[ xx, {2, 1} ] === {b, c}
Extract[ xx, {2, 1, 1} ] === b

(* extract multiple items *)
Extract[ xx, { {3}, {2, 1, 1} } ] === {e, b}

Other List Extraction Functions (by index)

First

get first element.

First

Last

get last element.

Last

Most

get all elements except last.

Most

Rest

get all elements except first.

Rest

Take

take nth to mth item

Take

Drop

Return a list with nth to mth dropped

Drop

WolframLang List Operations