Previous
String Manipulation 
Next
If 
Tcl/Tk Tutorial - Create GUI using Tk with Tcl Language
Lists

Lists

A Tcl list holds a sequence of elements, each of which can be numbers, strings, or other lists. Lets make a list :

set list_name "To Do List"
# Create an Empty list using the list command. Not very nessary  
set to_do [list]
#Add items to our to do list
lappend to_do "Buy Groceries"
lappend to_do "Tame Nature"
lappend to_do "Split Atom"

#Display all things
label .desc -text "The $list_name\n$to_do"
label .one -text "First thing to do : [lindex $to_do 0]" ;#Get first element
label .second -text "Second thing to do : [lindex $to_do 1]";#Get second element
label .third -text "Third thing to do : [lindex $to_do 2]" ;#and so on
pack .desc .one .second .third

#Insert a new Item in the second place
set to_do [linsert $to_do 1 "Capture Osama Bin Laden"]
label .list -text "New List\n$to_do"

#Change an item
set to_do [lreplace $to_do 3 3 "Someone already did that"]
label .latest -text "Latest List\n$to_do"
label .total -text "Total number of jobs to do = [llength $to_do]"
pack .list .latest .total
The commands used here for lists and their descriptions:
CommandLine SyntaxDescription
list3list ?value value value ...? This command returns a list comprised of all the args, or an empty string if no args are specified.
lappend5lappend listName ?value value value ...? This command treats the variable given by listName as a list and appends each of the value arguments to that list as a separate element, with spaces between elements. If listName doesn't exist, it is created as a list with elements given by the value arguments.
lindex10lindex list ?index...? The lindex command takes a Tcl list and shows its index'th element. Remember that lists start at 0 and the first element is 0'th one.
linsert17linsert list index element ?element element ...? This command produces a new list from list by inserting all of the element arguments just before the index'th element of list.
lreplace21lreplace list first last ?element element ...? lreplace returns a new list formed by replacing one or more elements of list with the element arguments. first and last in the syntax specify the first and last index of the range of elements to replace
llength23llength list Treats list as a list and returns a decimal string giving the number of elements in it.

There are more list related commands like lsort, lset, lrange, lsearch and even others like split, join etc. See the manual for details on these commands.

split
Split is a very useful command for creating lists from strings. If you want to split a string into several items at any character in the string you can use the... em... split command. If you want to get every word into a list in a sentence this command is very useful.
set words [split $sentence " "]
Here the variable called $sentence is cut at each and every instance of space in it - essentially splitting it into words. Now there is a new list called $words. The result of [lindex $words 0] will the first word, 1 will be second and so on. Another useful thing one can do with this command is to read a file with the read command and split the resulting string with "\n" to get a list of all lines in the file. You need to get to File Handling to learn that.


Arrays

One can make another kind of array in Tcl with the "array" command. This gives each value in the array a name and the values can be accessed with this name.

Syntax:
array option arrayName ?arg arg ...?

I like this syntax better. Make it a lot more readable...
array option arrayName {
arg arg
...?
}

#Make the array
array set star_trek {
	location	"Bridge of the Enterprise"
	problem		"Power surge"
	solution	"a fuse"
}
#Access the variables
label .sol1 -text "The $star_trek(problem) at $star_trek(location) \
	could have been avoided if they had $star_trek(solution)."
#Change the variable
set star_trek(solution)	"Wesley"
#Access the changed variables
label .sol2 -text "The $star_trek(problem) at $star_trek(location) \
	could have been avoided if they had $star_trek(solution)."
#Show the solutions
pack .sol1 .sol2

The command 'array set star_trek' creates the array and gives the following arguments as its contents. It can be access with this code
$<ARRAY_NAME>(<ELEMENT_ID>)
It could be changed just as easily by removing the '$' sign as when accessing any other variable. Eg:
set <ARRAY_NAME>(<ELEMENT_ID>) <VALUE>.

Some 'array' related commands and their descriptions:
CommandSyntaxDescription
array set array set arrayName { list } Sets the values of one or more elements in arrayName. list must have a form like that returned by array get, consisting of an even number of elements. Each odd-numbered element in list is treated as an element name within arrayName, and the following element in list is used as a new value for that array element.
array size array size arrayName Returns a decimal string giving the number of elements in the array. If arrayName isn't the name of an array then 0 is returned.
array namesarray names arrayName ?mode? ?pattern? Returns a list containing the names of all of the elements in the array that match pattern. Mode may be one of -exact, -glob, or -regexp.
Previous
String Manipulation 
Next
If 

Comments

Anonymous at 18 Apr, 2007 09:06
good
Reply to this.
Fruttenboel at 21 Jul, 2007 04:58
A small HTML eror:

you can use the... em... split command
Reply to this.
Jasmine at 12 Sep, 2007 02:02
Good.
Reply to this.
Anonymous at 22 Apr, 2008 02:43
how to delete the last item from the list
Reply to this.
Anonymous at 24 May, 2008 11:57
First way, replace the last element with nothing:
set to_do [lreplace $to_do end end]
Second way, copy all the list elements except the last element:
set to_do [lrange $to_do 0 end-1]

First method looks more adequate.
Reply to this.
Anonymous at 27 May, 2008 07:12
This guy is funny , good job
Reply to this.
Anonymous at 07 Aug, 2008 10:23
Got a question.
For example, i have an array to store "to do list" from Monday to Friday.
set to_do(1) "do test 1, go shopping"
set to_do(2) "do test 2"
set to_do(3) "do test 3, go cinema"
set to_do(4) "do test 4"
set to_do(5) "do test 5"

how can I remove the whole element to_do(2) from the array, but not just simply set the value of the element to ""?
Reply to this.
Sarin at 09 Aug, 2009 08:04
I was learning tcl/tk for making an application. Thought this could be a good exercise for me :) The method described below might not be the optimum. But it does the job.

#define an array
set to_do(1) "1"
set to_do(2) "5"
set to_do(3) "4"
set to_do(4) "3"
set to_do(5) "1"

#Convert it to a list
set nl [ array get to_do ]

set count 0

#Look at each element and find our index
foreach val $nl {
incr count
#The index will occur at odd position in the array
if { [ expr $count % 2 ] == 1 } {
#Check if this is the index of our interest
if { $val == "2" } {
#Remove that element and the one after that in the list
set nl [ lreplace $nl [ expr $count -1 ] [ expr $count + 1 ] [lindex $nl [ expr $count + 1 ] ] ]
}
}
}

#Re-create the array
array unset to_do
array set to_do $nl
Reply to this.
Rajat Gujral at 31 Dec, 2009 04:50
Better way of removing the element

proc lremove {listVariable value} {
upvar 1 $listVariable var
set idx [lsearch -exact $var $value]
set var [lreplace $var $idx $idx]
}
Reply to this.
Chiamy at 08 Mar, 2009 03:31
I got a question: is there possible to add a list as value, instead of a string?
For example:
#Make the array
array set star_trek {
location $list_location
problem $list_problem
solution $list_solution
}

May I know the correct syntax to add list as value?
Thanks!
Reply to this.
Michał at 03 May, 2009 09:17
These arrays, they look awfully alike dictionaries or maps don't they?
Any assumptions on the time complexity of accessing the elements of it?
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed