Adding & Deleting members of a list
The commands for adding and deleting list members are:
concat?arg1 arg2 ... argn?- Concatenates the
argsinto a single list. It also eliminates leading and trailing spaces in the args and adds a single separator space between args. Theargstoconcatmay be either individual elements, or lists. If anargis already a list, the contents of that list is concatenated with the otherargs. lappendlistName?arg1 arg2 ... argn?- Appends the
argsto the listlistNametreating eachargas a list element. linsertlistNameindexarg1?arg2 ... argn?- Returns a new list with the new list elements inserted just
before the
indexth element oflistName. Each element argument will become a separate element of the new list. If index is less than or equal to zero, then the new elements are inserted at the beginning of the list. If index has the valueend, or if it is greater than or equal to the number of elements in the list, then the new elements are appended to the list. lreplacelistNamefirstlast?arg1 ... argn?- Returns a new list with N elements of
listNamereplaced by theargs. Iffirstis less than or equal to 0, lreplace starts replacing from the first element of the list. Iffirstis greater than the end of the list, or the word end, then lreplace behaves like lappend. If there are fewerargsthan the number of positions betweenfirstandlast, then the positions for which there are noargsare deleted. lsetvarNameindexnewValue- The
lsetcommand can be used to set elements of a list directly, instead of usinglreplace.
Lists in Tcl are the right data structure to use when you have
an arbitrary number of things, and you'd like to access them
according to their order in the list. In C, you would use an array.
In Tcl, arrays are associated arrays - hash tables, as you'll see
in the coming sections. If you want to have a collection of things,
and refer to the Nth thing (give me the 10th element in this group
of numbers), or go through them in order via foreach.
Take a look at the example code, and pay special attention to the way that sets of characters are grouped into single list elements.
Example
set b [list a b {c d e} {f {g h}}]
puts "Treated as a list: $b\n"
set b [split "a b {c d e} {f {g h}}"]
puts "Transformed by split: $b\n"
set a [concat a b {c d e} {f {g h}}]
puts "Concated: $a\n"
lappend a {ij K lm} ;# Note: {ij K lm} is a single element
puts "After lappending: $a\n"
set b [linsert $a 3 "1 2 3"] ;# "1 2 3" is a single element
puts "After linsert at position 3: $b\n"
set b [lreplace $b 3 5 "AA" "BB"]
puts "After lreplacing 3 positions with 2 values at position 3: $b\n"