Version 14 of element

Updated 2004-08-15 08:13:25 by lwv

Purpose: describe what Tcl considers a list element - i.e. the basic component of a list.


Given that Tcl considers everything is a string, then a list element is, at its core, just a string. This string can either be 0 length, 1 or more characters, and can be formatted in such a way that the element is also another list.

However, just because every element is a string does NOT mean that every string is a list element.

In Tcl, one programatically ensures a string is a list element most safely by usign either the list or the split command to listify the string.

But, for example, let us say you want the 5 character literal string

 a { b c }

turned into a 5 element list.

Simply saying

 set l [list "a { b c }" ]

does not give you a 5 element list

 llength $l
 1

nor does calling list with an unquoted argument

 set l [list a { b c } ]
 llength $l
 2

but this does:

 set l [split "a { b c }"]
 llength $l
 5

The problem in the first list case is that Tcl treats the " character as introducing the beginning and ending of a single element, and in the second list case, list sees the { and } characters and treats its arguments as if they had already been processed by Tcl into elements.

Internally, tcl structures each list element as if it were surrounded by { and }. Split, however, is designed to take as its first argument a string that needs to be quoted properly, so it is able to create what is needed.


See also list, lappend, lindex, linsert, llength, lrange, lreplace, lsearch, lsort, concat, split, foreach, array .

caspian recommends that you also see: join and lset


Tcl syntax help

Category Glossary