programming.nbk: Home | Index | Next Page: Tcl: pattern matching | Previous Page: Tcl: list operations
A Tcl list holds a sequence of elements, each of which can be a number, a string, or another list.
You can create an empty list with the list command:
set user_codes [list]
You can create a list of things with the list command:
set stuff [list foo bar zot]
or a literal list:
set stuff2 {thing1 thing2 thing3}
[llength] returns the number of elements in the list.
set foo [list 1 2 [list 3 4 5]] ==> 1 2 {3 4 5} llength $foo ==> 3
lindex returns the nth element of the list. The fist element is 0 (zero), like in C. lindex returns an empty string if the requested element is off the end of the list.
set foo [list 1 2 [list 3 4 5]] ==> 1 2 {3 4 5} lindex $foo 0 ==> 1
[lsearch] returns the index of the list element that matches the argument or -1 if none match.
set community_colleges [list "caltech" "cmu" "rpi"] lsearch -exact $community_colleges "caltech" ==> 0 lsearch -exact $community_colleges "harvard" ==> -1
[lrange] returns a subset of the elements in the list:
set foo [list 1 2 [list 3 4 5]] ==> 1 2 {3 4 5} lrange $foo 1 2 ==> 2 {3 4 5}
[lappend] adds an element(s) to the end of a list:
set foo [list 1 2 [list 3 4 5]] ==> 1 2 {3 4 5} lappend foo [list 6 7] ==> 1 2 {3 4 5} {6 7}
[linsert] inserts an element or elements in a list before the given element:
set foo [list 1 2 [list 3 4 5]] ==> 1 2 {3 4 5} linsert $foo 0 0 ==> 0 1 2 {3 4 5} {6 7}
[lreplace] replaces a range of elements in a list with the arguements and returns the new list. The original list is unchanged.
set foo [list 1 2 [list 3 4 5]] ==> 1 2 {3 4 5} lreplace $foo 3 4 3 4 5 6 7 ==> 0 1 2 3 4 5 6 7 set foo ==> 1 2 {3 4 5} {6 7}
[lsort] sorts the elements of a list:
set my_friends [list "herschel" "schlomo" "mendel"] set my_sorted_friends [lsort -decreasing $my_friends] ==> schlomo mendel herschel
[concat] will merge two or more lists.
set my_friends [list "herschel" "schlomo" "mendel"] set my_wifes_friends [list "biff" "christine" "clarissa"] concat $my_wifes_friends $my_friends ==> biff christine clarissa herschel schlomo mendel
split will break a string into lists at the given character.
set my_ip_address 18.1.2.3 ==> 18.1.2.3 set ip_elements [split $my_ip_address "."] ==> four element list, with values 18 1 2 3
[join] creates a string of all the list elements. join can have an optional string to put between the list elements:
set data {1 2 3 4 5} join $data ", " => 1, 2, 3, 4, 5
set s [join [list "henry" "the" "eighth"]] puts s ->henry the eighth
programming.nbk: Home | Index | Next Page: Tcl: pattern matching | Previous Page: Tcl: list operations
Notebook exported on Monday, 7 July 2008, 18:56:06 PM Eastern Daylight Time