# WolframLang: Get Parts of List

By Xah Lee. Date: . Last updated: .

There are many functions that extract sub-expression:

• `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.
• `Select` → get elements by a filtering function.
• `Cases` → get elements by Pattern.

## 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 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 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. .

💡 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 Filter Function

`Select`

Get elements by a filter function

```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[ {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}}```

`Min`
`Max`

## Other List Extraction Functions (on Item Position)

`First`

get first element.

`Last`

get last element.

`Most`

get all elements except last.

`Rest`

get all elements except first.

`Take`

take nth to mth item

`Drop`

Return a list with nth to mth dropped