WolframLang: Get Parts of List
There are many functions that extract sub-expression by position:
Part
→ get top-level elements by index, or index range, or get a column of matrix, or get value from Association (Hashtable, Map, Dictionary) This is the most versatile and most frequently used function to get part of a expression.Extract
→ get any arbitrarily nested element by its Position. This is the most simple and logical.
Get Parts by Index
Part[expr, i]
-
🔸 SHORT SYNTAX:
expr[[i]]
ith part of expr. If i is negative, count from right.
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 forSpan[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 endexpr[[;;n]]
→ beginning to nexpr[[;;,j]]
→ column jexpr[[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.
💡 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.
Last
-
get last element.
Most
-
get all elements except last.
Rest
-
get all elements except first.
WolframLang List Operations
- WolframLang: List Operations
- WolframLang: Get Parts of List
- WolframLang: Add Element to List
- WolframLang: Delete Element in List
- WolframLang: Change Element in List
- WolframLang: Check Item Existence in List
- WolframLang: Filter List
- WolframLang: Sort, Reverse, Order
- WolframLang: List Reshape (split, group, flatten, transpose)
- WolframLang: List Combinatorics
- WolframLang: List Join, Union, Intersection, Difference