Retrieving an element from a list
While the ability to assign the elements of a list to variables is a wonderful method of retrieving the values, it would be beneficial to access the elements directly without the necessity of variable assignment. To accomplish this, Tcl provides the lindex
command. The syntax is as follows:
lindex list index1 index2 …
How to do it…
In the following example, we will create a list and pass an index to the lindex
command to retrieve the value stored at the index. Return values from the commands are provided for clarity. Enter the following command:
% set input {John Mary Bill} John Mary Bill % lindex $input 1 Mary
How it works…
The lindex
command accepts the list
parameter and treats it as a Tcl list. If the index values are provided, it will return the element referenced by the indices. Please note that a list is returned if an element is a list and that additional index values will return the elements from sublists.