Version 17 of element

Updated 2004-08-16 15:21:52

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.

I beg to differ with that assertion. Every string can be a list element; I've never seen anything to contradict that. The examples below show several incorrect ways to treat a string as a list element, but when done properly (as in the final example using split) it proves that anything -- including a single left or right curly brace -- can indeed be a list element. There is no string that cannot be stored as an element in a list.

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.

You're getting your terminology mixed up. To make a string into a list element one needs do nothing more than to insert it into a list. You say one must use list or split to listify the string, but that's not the same as making a string into a list element; that's onverting a string (split) or list of strings (list) into a list.

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