lassign list var1 var2 ... copies elements into the variables in order and returns any leftover elements. If the list runs out, the extra variables are set to the empty string.
Tcl Easy · Lesson 1 · On the house
Lists in depth: lassign, lsort options, lsearch and lset
Unpack lists with lassign, sort by field or a custom rule, find every match with lsearch, and edit lists with lreplace and lset. Lesson 1 is free — on the house.
Lessons · Tcl Easy · Lesson 1 of 10 · On the house
Lists in depth: lassign, lsort options, lsearch and lset
Unpack lists with lassign, sort by field or a custom rule, find every match with lsearch, and edit lists with lreplace and lset.

lsort compares as strings by default. -integer or -real compare as numbers, -decreasing reverses the order, and -index 1 sorts a list of records by their second field. The sort is stable, so records that compare equal keep their original order: ana stays ahead of cai.
lsort -command cmp calls cmp a b for each comparison, and cmp must return a negative integer, zero or a positive integer. -unique drops duplicates from the sorted result.
lsearch returns the index of the first match, using glob patterns by default, or -1 when nothing matches. -all returns every index, -inline returns the matching elements instead of indices, -exact turns off patterns, and -index 1 matches against one field of each record.
lreplace list first last ?new ...? returns a new list with that range replaced; with no new elements it deletes the range. lset var index ?index ...? value changes an element of a list variable, and extra indices reach into nested lists.
lrepeat count value builds a list of repeated values and lreverse returns the list backwards. lreplace, lreverse and lrange return new values and leave the variable alone; lset and lappend are the ones that change the variable.
lists in depth
set scores {{ana 91} {ben 78} {cai 91} {dee 85}}
lassign [lindex $scores 0] who pts
puts "$who scored $pts"
puts [lsort -integer -decreasing -index 1 $scores]
puts [lsort -index 0 -decreasing $scores]
proc byLen {a b} { expr {[string length $a] - [string length $b]} }
puts [lsort -command byLen {kiwi fig banana apple}]
puts [lsort -unique {c a b a c}]
puts [lsearch -all -inline -index 1 $scores 91]
puts [lsearch -all {a b a c a} a]
set row {1 2 3 4 5}
puts [lreplace $row 1 2 x]
lset scores 1 1 80
puts [lindex $scores 1]
puts [lrepeat 3 ab]
puts [lreverse {1 2 3}]
Quiz
Quiz
Quiz
Quiz
Check
Match the still for: Lists in depth: lassign, lsort options, lsearch and lset.
Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.