TCL remove an element from a list

regsub may also be suitable to remove a value from a list.

set mylist {a b c}
puts $mylist
  a b c

regsub b $mylist "" mylist

puts $mylist
  a  c
llength $mylist
  2

set mylist {a b c}
puts $mylist
a b c

Remove by index

set mylist [lreplace $mylist 2 2]
puts $mylist 
a b

Remove by value

set idx [lsearch $mylist "b"]
set mylist [lreplace $mylist $idx $idx]
puts $mylist
a

The other way to remove an element is to filter it out. This Tcl 8.5 technique differs from the lsearch&lreplace method mentioned elsewhere in that it removes all of a given element from the list.

set stripped [lsearch -inline -all -not -exact $inputList $elemToRemove]

What it doesn't do is search through nested lists. That's a consequence of Tcl not putting effort into understanding your data structures too deeply. (You can tell it to search by comparing specific elements of the sublists though, via the -index option.)


Lets say you want to replace element "b":

% set L {a b c d}
a b c d

You replace the first element 1 and last element 1 by nothing:

% lreplace $L 1 1
a c d

Tags:

List

Element

Tcl