The commands for adding and deleting list members are:
concat
?arg1
arg2 ... argn?
args
into a single
list. It also eliminates leading and trailing spaces in the args
and adds a single separator space between args. The args
to concat
may be
either individual elements, or lists. If an arg
is already a list, the contents of that list is
concatenated with the other args
.lappend
listName
?arg1 arg2 ...
argn?
args
to the list listName
treating each arg
as a list element.linsert
listName
index
arg1
?arg2 ... argn?
index
th element of listName
. 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 value end
, 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.lreplace
listName
first
last
?arg1 ... argn?
listName
replaced by the args
. If first
is less than
or equal to 0, lreplace starts replacing from the first element of
the list. If first
is greater than the end
of the list, or the word end, then lreplace behaves like
lappend. If there are fewer args
than the
number of positions between first
and
last
, then the positions for which there
are no args
are deleted.lset
varName
index
newValue
lset
command can be used to
set elements of a list directly, instead of using lreplace
.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.
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"