lindex

Gives the element of a list at an index, or at a path of indexes into nested lists.

lindex LIST ?INDEX ...?

Description

Gives the element of LIST at INDEX. Each further INDEX goes one level down into the element of the index before it, so lindex $l 1 0 is the first element of the second element. One INDEX that is itself a list of indexes, such as {1 0}, is the same path.

An index is an integer from 0, end, end-N, or M+N and M-N with integers. An index before the first element or after the last one gives an empty string, at each level. With no INDEX, or with an empty list as INDEX, the result is LIST itself.

A value on the path that is one word is a list of one element, so lindex a 0 0 gives a.

Arguments

ArgumentTypeDefaultDescription
LISTlistrequiredThe list.
INDEXindex, or a list of indexesnoneThe place of the element, one level of the path each.

Returns

The element, or an empty string for an index out of range.

Examples

% lindex {a b c} end
c

% lindex {a b c} end-1
b

% lindex {{a b} {c d}} 1 0
c

% lindex {{a b} {c d}} {1 0}
c

% lindex {a b c} 5

% lindex {a b c}
a b c

% lindex {a b} 0 0 0
a

Errors

% lindex {a b c} x
bad index "x": must be integer?[+-]integer? or end?[+-]integer?
-errorcode NONE

% lindex "a {b" 0
unmatched open brace in list
-errorcode TCL VALUE LIST BRACE

Differences from Tcl

Facts

Capability
None.
Tcl release
Tcl 9.1 and 8.6.
Since
ztcl 1.0.0-beta.1

See also