Part
[expr, i]Extract an element from a list:
A = {a, b, c, d};
A[[3]]
Negative indices count from the end:
{a, b, c}[[-2]]
Part
can be applied on any expression, not necessarily lists.
(a + b + c)[[2]]
expr[[0]]
gives the head of expr:
(a + b + c)[[0]]
Parts of nested lists:
M = {{a, b}, {c, d}};
M[[1, 2]]
You can use Span
to specify a range of parts:
{1, 2, 3, 4}[[2;;4]]
{1, 2, 3, 4}[[2;;-1]]
A list of parts extracts elements at certain indices:
{a, b, c, d}[[{1, 3, 3}]]
Get a certain column of a matrix:
B = {{a, b, c}, {d, e, f}, {g, h, i}};
B[[;;, 2]]
Extract a submatrix of 1st and 3rd row and the two last columns:
B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
B[[{1, 3}, -2;;-1]]
The 3d column of a matrix:
{{a, b, c}, {d, e, f}, {g, h, i}}[[All, 3]]
Further examples:
(a+b+c+d)[[-1;;-2]]
x[[2]]
Assignments to parts are possible:
B[[;;, 2]] = {10, 11, 12}
B
B[[;;, 3]] = 13
B
B[[1;;-2]] = t;
B
F = Table[i*j*k, {i, 1, 3}, {j, 1, 3}, {k, 1, 3}];
F[[;; All, 2 ;; 3, 2]] = t;
F
F[[;; All, 1 ;; 2, 3 ;; 3]] = k;
F
Of course, part specifications have precedence over most arithmetic operations:
A[[1]] + B[[2]] + C[[3]] // Hold // FullForm