Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TCL remove an element from a list

Tags:

How te remove an element from TCL list say:

  1. which has index = 4
  2. which has value = "aa"

I have Googled and have not found any built-in function yet.

like image 691
Narek Avatar asked Apr 18 '11 11:04

Narek


People also ask

How do I add and remove members from a list in Tcl?

lset varName index newValue. The lset command can be used to set elements of a list directly, instead of using lreplace . Lists in Tcl are the right data structure to use when you have an arbitrary number of things, and you'd like to access them according to their order in the list. In C, you would use an array.

How do you delete the last element of a list in Tcl?

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. What it doesn't do is search through nested lists.

How do I delete a variable in Tcl?

tcl Variables Deleting variable/sThe unset command is used to remove one or more variables.

How do I use Lappend in Tcl?

Lappend is similar to append except that the values are appended as list elements rather than raw text. This command provides a relatively efficient way to build up large lists. For example, ``lappend a $b'' is much more efficient than ``set a [concat $a [list $b]]'' when $a is long.


2 Answers

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 
like image 50
drysdam Avatar answered Nov 06 '22 22:11

drysdam


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.)

like image 37
Donal Fellows Avatar answered Nov 07 '22 00:11

Donal Fellows