Tcl
List Basics


return to main index



Defining a List

A list in Tcl consists of a string whose items are separated by white space. For example, this is a list,

    A B C D E

To assign a list to a variable we can do this,

    set list1 {A B C D E}

or this,

    set list1 [list A B C D E]

The second method is better because the use of the list command makes it much clearer that a list is being created. To print a raw list to the console we use the puts command,

    puts "The contents of list1 are: $list1"
Embedded Lists

It is possible for one list to have another list embedded within it, for example,

    set list1 [list A B [list 1 2 3] C D E]

A list may also contain consecutive lists, for example,

    set list1 [list DOG CAT MULE]
    set list2 [list dog cat mule]
    set list3 [list $list1 $list2]

Accessing Items in a List

To step through a list the foreach command is used,

    foreach item $list1 {
        puts $item
        }

Although the use of foreach, shown above, works well when printing a simple list it fails to print items contained within embedded lists. A partial solution to this problem is to encapsulate the list handling code within a procedure.

    proc printlist { inlist } {
        foreach item $inlist {
            puts $item
            }
        }

By making the procedure recursive it can the items in an embedded list correctly.

    proc printlist { inlist } {
        foreach item $inlist {
            # recurse - go into the sub list
            if { [llength $item] > 1 } {
                printlist $item 
            } else {
                puts $item
            }
        }

Note the use of the llength command to check if an item consists of sub items. Finally, to use this procedure,

    set list1 [list A B [list 1 2 3] C D E]
    printlist $list1



© 2002- Malcolm Kesson. All rights reserved.