Version 21 of lappend

Updated 2004-10-27 11:31:21

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.

Lars H: It seems you disagree about what it means to "attempt" something. What lappend does is that it attempts to generate a list internal representation for the current value of the variable (i.e., it calls tclListType.setFromAnyProc [L1 ]), and then appends the element(s) to that. This attempt will fail when the string representation cannot be interpreted as a list.


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]

RS Well, as experimentation easily shows, that results in {xyz {1 2 3}}, while

   set a [concat $toPrepend $a]

results in the 4-element list (maybe via shimmering over string reps)

   xyz 1 2 3 

linsert would keep an existing list representation, so I presume its faster to do

 set a [linsert $a 0 $toPrepend]

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


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