WolframLang: Get Parts of List

By Xah Lee. Date: . Last updated: .

There are many functions that extract sub-expression:

Get Element by Position Spec: 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 the most logical way to get a subexpression, or a list of them. But is not convenient if you want a range of adjacent expressions.

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}

Get Parts by Index

the Part function is the most versatile and most frequently used function to get part of a expression.

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 Parts by Filter Function

Select
Get elements by a filter function Select
Select[ {3,4,5,6}, EvenQ ] === {4, 6}

Select[ Range[20], PrimeQ ] === {2, 3, 5, 7, 11, 13, 17, 19}
Select[
 {{3}, {0, 23}, {9}, {4,5,6}},
 Function[ Length[#] === 2 ]
] === {{0, 23}}

Get Parts by Pattern

Cases
Get elements by Pattern Cases
Cases[ {a, f[3], f[9]}, f[_] ] === {f[3], f[9]}

Cases[ {a, f[3], g[4], f[5]}, _[_] ] === {f[3], g[4], f[5]}

Cases[ {{2}, {4, 8}, {c}}, {_ , _} ] === {{4, 8}}

Get Min/Max

Min
Min
Max
Max

Other List Extraction Functions (on Item Position)

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

List