How to define a Tcl list

Introduction

A Tcl list is a type of data structure which stores data in an orderly fashion. Since everything is a string in Tcl, using a list is essential to process data instead of doing complicated string manipulations.  Common operations such as appending data to a list, data extractions , sorting and similar tasks can be performed using list functions.

Defining a list

Lets say I need to create a list that contains information about a person’s name, age and occupation.The list command is used to do just that:

% set myList [list Gary 30 Engineer]
Gary 30 Engineer

Extracting values from a list

lindex

To extract a single value from a list, the lindex command is used. The format for using lindex  is

lindex <variable> <index>

Using the same myList as above, we extract each information one by one. The first list element starts at 0.  So if you have a 3 element list, the last element’s index is 2.

% set myList [list Gary 30 Engineer]
Gary 30 Engineer
% lindex $myList 0
Gary
% lindex $myList 1
30
% lindex $myList 2
Engineer

lrange

What if you want to extract certain range of elements in a Tcl list? Let’s say I am only interested in the age and the occupation. To do the job use Tcl’s built in  lrange command.

lrange <tcl list variable> <Index one> <Index two>
% set myList [list Gary 30 Engineer]
Gary 30 Engineer
% set myList_short [lrange $myList 0 1]
Gary 30