Tcl data structures
last modified November 24, 2026 Tcl 8.6
Tcl has no class library for containers. It has lists and dictionaries, and almost every classic data structure is one of those two with a discipline attached. A stack is a list that grows and shrinks at one end, a queue is a list that grows at one end and shrinks at the other, and a set is a dictionary whose keys are the members.
That is not a limitation. Lists and dictionaries are implemented in C, they scale well, and the operations below are a few lines each. This article builds the common structures step by step and finishes with a graph traversal. The Tcl list and Tcl dictionary pages document the commands used throughout.
A stack built on a list
A stack is last in, first out. lappend adds a value to the end of
a list, and the end of the list is the top of the stack. Popping reads the last
element with lindex $stack end and rebuilds the list without it.
The procedures take the name of the variable, not its value, so they can change
the caller's stack through upvar.
set stack {}
proc stack_push {stackVar value} {
upvar 1 $stackVar stack
lappend stack $value
}
proc stack_pop {stackVar} {
upvar 1 $stackVar stack
set value [lindex $stack end]
set stack [lrange $stack 0 end-1]
return $value
}
stack_push stack first
stack_push stack second
stack_push stack third
puts "top: [lindex $stack end]"
puts "popped: [stack_pop stack]"
puts "stack: $stack"
puts "size: [llength $stack]"
upvar 1 $stackVar stack links the local name stack to
the caller's variable, which is why lappend inside the procedure
changes the list outside it. Pushing is cheap because the value goes to the end;
popping copies the remaining elements, so it costs time proportional to the
stack size. For the sizes found in scripts that is irrelevant.
$ tclsh stack.tcl top: third popped: third stack: first second size: 2
A queue
A queue is first in, first out. New values go to the end with
lappend, and removal takes the element at index 0. The queue
procedures mirror the stack ones, which makes the difference between the two
structures easy to see.
set queue {}
proc queue_add {queueVar value} {
upvar 1 $queueVar queue
lappend queue $value
}
proc queue_remove {queueVar} {
upvar 1 $queueVar queue
set value [lindex $queue 0]
set queue [lrange $queue 1 end]
return $value
}
queue_add queue alpha
queue_add queue beta
queue_add queue gamma
puts "front: [lindex $queue 0]"
puts "removed: [queue_remove queue]"
puts "removed: [queue_remove queue]"
puts "queue: $queue"
queue_remove returns the front element and keeps the rest with
lrange $queue 1 end. Each removal copies the remaining list, so a
long-lived queue with many removals is better served by an index that moves
forward through the list, or by two lists. For a few thousand items the simple
version is fast enough and much easier to read.
$ tclsh queue.tcl front: alpha removed: alpha removed: beta queue: gamma
A set built on a dictionary
A set stores each value once and answers membership questions quickly. A
dictionary is a hash table, so its keys form a set: dict set adds a
member, dict exists tests one, and dict unset removes
one. The value stored for each key is irrelevant, and 1 is the
usual placeholder.
set tags [dict create]
foreach tag {tcl tk socket tcl dict tk} {
dict set tags $tag 1
}
puts "distinct tags: [dict size $tags]"
puts "sorted: [lsort [dict keys $tags]]"
puts "has socket: [dict exists $tags socket]"
puts "has sqlite: [dict exists $tags sqlite]"
dict unset tags tk
puts "after remove: [lsort [dict keys $tags]]"
The loop adds six tags but the dictionary ends up with four keys, because
tcl and tk appear twice. dict exists
returns 0 or 1, which the script prints directly. Compared with
lsearch on a list, membership in a dictionary does not slow down as
the set grows.
$ tclsh setdict.tcl distinct tags: 4 sorted: dict socket tcl tk has socket: 1 has sqlite: 0 after remove: dict socket tcl
Counting occurrences
Counting is the other side of a set: the dictionary key is the value and the
stored value is the counter. dict incr adds one to an element and
creates it with the value 0 first when the key is missing, so the loop needs no
special case for the first occurrence.
set text "the quick brown fox jumps over the lazy dog the fox"
set counts [dict create]
foreach word [split $text] {
dict incr counts $word
}
foreach word [lsort [dict keys $counts]] {
puts [format "%-6s %d" $word [dict get $counts $word]]
}
puts "---"
puts "the appears [dict get $counts the] times"
puts "distinct words: [dict size $counts]"
split $text without a separator splits on white space, which is
enough for this sentence. The second loop sorts the keys so the report is stable
instead of following hash order, and format aligns the counts in a
column. The same pattern counts log levels, HTTP status codes or words in a
file.
$ tclsh count.tcl brown 1 dog 1 fox 2 jumps 1 lazy 1 over 1 quick 1 the 3 --- the appears 3 times distinct words: 8
Sorting and searching
lsort returns a new sorted list and leaves the original untouched.
By default it compares values as strings, which puts 19 before
3; the -integer option compares numbers instead.
-decreasing reverses the order, and -index sorts a
list of records by one field. lsearch looks for a value and returns
its index, or -1 when the value is absent.
set numbers {42 7 19 3 88 15}
puts "original: $numbers"
puts "ascending: [lsort -integer $numbers]"
puts "descending: [lsort -integer -decreasing $numbers]"
set people {{Jane 28} {Adam 35} {Eva 22}}
puts "by age: [lsort -integer -index 1 $people]"
puts "by name: [lsort -index 0 $people]"
puts "index of 19: [lsearch -exact $numbers 19]"
puts "index of 100: [lsearch -exact $numbers 100]"
puts "first 8x: [lsearch -glob $numbers 8*]"
puts "largest: [lindex [lsort -integer $numbers] end]"
The people records are three-element lists, so -index 1 sorts by
age and -index 0 by name. lsearch -exact compares
whole values, while -glob accepts a pattern such as
8*. Searching is a linear scan: it works on unsorted data and is
the right tool when the list is small or changes often.
$ tclsh sorting.tcl
original: 42 7 19 3 88 15
ascending: 3 7 15 19 42 88
descending: 88 42 19 15 7 3
by age: {Eva 22} {Jane 28} {Adam 35}
by name: {Adam 35} {Eva 22} {Jane 28}
index of 19: 2
index of 100: -1
first 8x: 4
largest: 88
Binary search
When a list is sorted and searched many times, binary search is much faster than a linear scan. It compares the value with the middle element and discards the half that cannot contain it, so a list of a million items needs about twenty comparisons. The price is that the list must be sorted first.
proc binary_search {sortedList value} {
set low 0
set high [expr {[llength $sortedList] - 1}]
while {$low <= $high} {
set middle [expr {($low + $high) / 2}]
set current [lindex $sortedList $middle]
if {$current eq $value} {
return $middle
} elseif {$current < $value} {
set low [expr {$middle + 1}]
} else {
set high [expr {$middle - 1}]
}
}
return -1
}
set numbers {3 7 15 19 42 88}
puts "list: $numbers"
puts "position 19: [binary_search $numbers 19]"
puts "position 42: [binary_search $numbers 42]"
puts "position 3: [binary_search $numbers 3]"
puts "position 50: [binary_search $numbers 50]"
The procedure keeps two indices, low and high, and
narrows the range until it finds the value or the range becomes empty. It
returns the position of the value or -1. The comparison with
eq and < is correct for both strings and integers
in sorted order; for numbers the list must have been sorted with
lsort -integer, exactly as in the example.
$ tclsh binary_search.tcl list: 3 7 15 19 42 88 position 19: 3 position 42: 4 position 3: 0 position 50: -1
A simple graph with adjacency lists
A graph is a set of nodes connected by edges. The usual representation is an
adjacency list: for each node, the list of its neighbours. A dictionary maps a
node to that list, and dict lappend appends a neighbour, creating
the entry when needed. The graph below is undirected, so every edge is stored in
both directions.
set graph [dict create]
proc add_edge {graphVar from to} {
upvar 1 $graphVar g
dict lappend g $from $to
dict lappend g $to $from
}
add_edge graph A B
add_edge graph A C
add_edge graph B D
add_edge graph C D
add_edge graph D E
puts "nodes: [lsort [dict keys $graph]]"
puts "neighbours A: [lsort [dict get $graph A]]"
puts "neighbours D: [lsort [dict get $graph D]]"
puts "degree of D: [llength [dict get $graph D]]"
The helper takes the dictionary by name and modifies it through
upvar, the same technique as the stack and the queue. After five
edges the dictionary has five keys, and the degree of a node is simply
llength of its neighbour list. A directed graph would need only the
first dict lappend in add_edge.
$ tclsh graph.tcl nodes: A B C D E neighbours A: B C neighbours D: B C E degree of D: 3
Breadth-first search
Breadth-first search visits a graph level by level. It starts at one node, puts it in a queue, and when a node leaves the queue its unvisited neighbours are marked and appended. The distance dictionary doubles as the visited set: a node that already has an entry is never queued twice.
proc breadth_first {graph start} {
set queue [list $start]
set distance [dict create $start 0]
set order {}
while {[llength $queue] > 0} {
set node [lindex $queue 0]
set queue [lrange $queue 1 end]
lappend order $node
foreach neighbour [dict get $graph $node] {
if {![dict exists $distance $neighbour]} {
set steps [expr {[dict get $distance $node] + 1}]
dict set distance $neighbour $steps
lappend queue $neighbour
}
}
}
return [list $order $distance]
}
set graph [dict create]
foreach {from to} {A B A C B D C D D E} {
dict lappend graph $from $to
dict lappend graph $to $from
}
lassign [breadth_first $graph A] order distance
puts "visit order: $order"
foreach node [lsort [dict keys $distance]] {
puts "$node is [dict get $distance $node] step(s) from A"
}
The graph is built inline from a list of edge pairs, so the script runs on its
own; each pair is stored in both directions. The queue holds nodes whose
neighbours have not been examined yet, and lrange $queue 1 end
removes the front, exactly like the queue procedure earlier. Each node enters
the queue once, so the run time is proportional to the number of nodes plus the
number of edges. In an unweighted
graph the recorded distance is also the shortest path length, which is why BFS
is used for routing and for puzzle solving.
$ tclsh bfs.tcl visit order: A B C D E A is 0 step(s) from A B is 1 step(s) from A C is 1 step(s) from A D is 2 step(s) from A E is 3 step(s) from A
Source
The commands behind these structures are lappend,
lindex, lrange, lsort,
lsearch and the dict family. The Tcl 8.6 manual
documents each of them in detail.
This article built a stack, a queue and a set from lists and dictionaries,
counted words with dict incr, sorted and searched data, and
traversed a graph with breadth-first search. The
Tcl list page covers the list commands in full, and the
Tcl dictionary page explains the dictionary commands
used by the set and the graph.
Author
List all Tcl Tutorials.