Getting List Elements: llength, lindex, and lrange

The llength command returns the number of elements in a list.

						llength {a b {c d}"e f g" h}
=> 5
llength {}
=> 0
					

The lindex command returns a particular element of a list. It takes an index; list indices count from zero.

set x {1 2 3}
lindex $x 1
=> 2
					

You can use the keyword end to specify the last element of a list, or the syntax end-N to count back from the end of the list. The following commands are equivalent ways to get the element just before the last element in a list.

lindex $list [expr {[llength $list] - 2}]
lindex $list end-1

The lrange command returns a range of list elements. It takes a list and two indices as arguments. Again, end or end-N can be used as an index:

						lrange {1 ...

Get Practical Programming in Tcl & Tk, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.