Tcl Lists
A Tcl list is a sequence of values. When you write out a list, it has the same syntax as a Tcl command. A list has its elements separated by white space. Braces or quotes can be used to group words with white space into a single list element. Because of the relationship between lists and commands, the list-related commands described in this chapter are used often when constructing Tcl commands.
 | Since Tcl 8.0, lists are really 1-dimensional object arrays. |
Early versions of Tcl represented all values as strings. Lists were just strings with special syntax to group their elements. The string representation was parsed on each list access, so you could have performance problems with large lists. The performance of lists was improved by the Tcl compiler added in Tcl 8.0. The Tcl runtime now stores lists using an C array of pointers to each element. (The Tcl_Obj type is described on page 694.) Tcl can access any element in the list with the same cost. Appending new elements to a list is made efficient by over allocating the array so there is room to grow. The internal format also records the number of list elements, so getting the length of a list is cheap. However, you can still get into performance trouble if you use a big Tcl list like a string, e.g., for output. Tcl will convert the list into a string representation if you print it to a file, or manipulate it with string commands. Table 5-1 describes Tcl commands for lists.
Table 5-1. List-related commandslist arg1 arg2 ... | Creates a list out of all its arguments. | lindex list ?i ...? | Returns the ith element from list. Specifying multiple index elements allows you to descend into nested lists easily. | llength list | Returns the number of elements in list. | lrange list i j | Returns the ith through jth elements from list. | lappend listVar arg ... | Appends elements to the value of listVar. | linsert list index arg arg ... | Inserts elements into list before the element at position index. Returns a new list. | lreplace list i j arg arg ... | Replaces elements i through j of list with the args. Returns a new list. | lsearch ?options? list value | Returns the index of the element in list that matches the value according to the options. Glob matching is the default. Returns -1 if not found. | lset listVar ?i ...? newValue | Set the ith element in variable listVar to newValue. (Tcl 8.4) | lsort ?switches? list | Sorts elements of the list according to the switches:
-ascii, -dictionary, -integer, -real, -increasing, -decreasing, -index ix, -unique, -command command. Returns a new list. | concat list list ... | Joins multiple lists together into one list. | join list joinString | Merges the elements of a list together by separating them with joinString. | split string splitChars | Splits a string up into list elements, using the characters in splitChars as boundaries between list elements. |
 |