Tcl Data Structures 101 - The list

The list is the basic Tcl data structure. A list is simply an ordered collection of stuff; numbers, words, strings, or other lists. Even commands in Tcl are just lists in which the first list entry is the name of a proc, and subsequent members of the list are the arguments to the proc.

Lists can be created in several ways:

by setting a variable to be a list of values
set lst {{item 1} {item 2} {item 3}}
with the split command
set lst [split "item 1.item 2.item 3" "."]
with the list command.
set lst [list "item 1" "item 2" "item 3"]

An individual list member can be accessed with the lindex command.

The brief description of these commands is:

list ?arg1? ?arg2? ... ?argN?
makes a list of the arguments
split string ?splitChars?
Splits the string into a list of items wherever the splitChars occur in the code. SplitChars defaults to being whitespace. Note that if there are two or more splitChars then each one will be used individually to split the string. In other words: split  "1234567" "36" would return the following list: {12 45 7}.
lindex list index
Returns the index'th item from the list. Note: lists start from 0, not 1, so the first item is at index 0, the second item is at index 1, and so on.
llength list
Returns the number of elements in a list.

The items in list can be iterated through using the foreach command:

foreach varname list body
The foreach command will execute the body code one time for each list item in list. On each pass, varname will contain the value of the next list item.

In reality, the above form of foreach is the simple form, but the command is quite powerful. It will allow you to take more than one variable at a time from the list: foreach {a b} $listofpairs { ... }. You can even take a variable at a time from multiple lists! For example: foreach a $listOfA b $listOfB { ... }


Examples

set x "a b c"
puts "Item at index 2 of the list {$x} is: [lindex $x 2]\n"

set y [split 7/4/1776 "/"]
puts "We celebrate on the [lindex $y 1]'th day of the [lindex $y 0]'th month\n"

set z [list puts "arg 2 is $y" ]
puts "A command resembles: $z\n"

set i 0
foreach j $x {
    puts "$j is item number $i in list x"
    incr i
}