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

Get Tcl/Tk 8.5 Programming Cookbook 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.