Version 19 of lappend

Updated 2004-10-26 19:33:20

lappend varName ?value value ...?


http://www.purl.org/tcl/home/man/tcl8.4/TclCmd/lappend.htm


Appends each value as a list element onto the end of the list stored in varName.

lappend used to be the only list-command which requires the name of a variable containing a list rather than the list itself, but in Tcl 8.4 the lset command was introduced.

 lappend listName

rather than

 lappend $listName

This command differs from append in that values are appended as list elements rather than raw text.

lappend will not make varName a list ; if it is one before the command, it will continue to be one.

AJD Uh? lappend *will* attempt to make varName's value into a list. The docs say "This command treats the variable given by varName as a list." ie. if it isn't a list to begin with, tcl will attempt to convert it to one, giving an error this is not possible:

 % set x "a \{" ;# string
 a {
 % lappend x b ;# treat it as list
 unmatched open brace in list ;# it wasn't a proper list!

LV Actually, the example here of x and b demonstrates that Tcl does not try to make varName into a list, but instead presumes that it is a valid list. If it attempted to turn the variable into a list, it would surely succeed; in this case, however the basic assumption of (nearly?) all the l* commands is that list arguments are proper lists and that no attempt will be made to second guess the caller.


You do not need to assign the results of lappend to varName; lappend modifies varName directly.


How would one append an item to the beginning of a list? Since append means to the end of, one wouldn't append to the beginning of a list. Instead, for a way to perform the equivalent of prepend, see linsert -- jfr

LV Wouldn't an alternative be:

        set a [list 1 2 3]
        set toPrepend [list "xyz"]
        set a [list $toPrepend $a]

See also list, lindex, linsert, llength, lrange, lreplace, lsearch, lsort .


Tcl syntax help - Arts and crafts of Tcl-tk programming - Category Command