[ Team LiB ] Previous Section Next Section

Modifying Lists: linsert and lreplace

The linsert command inserts elements into a list value at a specified index. If the index is zero or less, then the elements are added to the front. If the index is equal to or greater than the length of the list, then the elements are appended to the end. Otherwise, the elements are inserted before the element that is currently at the specified index. The following command adds to the front of a list:

linsert {1 2} 0 new stuff
=> new stuff 1 2

lreplace replaces a range of list elements with new elements. If you don't specify any new elements, you effectively delete elements from a list.

Note: linsert and lreplace do not modify an existing list like the lappend and lset commands. Instead, they return a new list value. In the Example 5-6, the lreplace command does not change the value of x:

Example 5-6 Modifying lists with lreplace
set x [list a {b c} e d]
=> a {b c} e d
lreplace $x 1 2 B C
=> a B C d
lreplace $x 0 0
=> {b c} e d
    [ Team LiB ] Previous Section Next Section