1

I looked at TCL remove an element from a list, and it doesn't seem to work for me. Some code for example:

set mylist [list {a b c} {d e f} {g h i}]

This is what I want to happen:

set idx [lsearch $mylist "a"];      # or if "d", it should take out {d e f} instead. Likewise, if "g" it should take out {g h i}
set mylist [lreplace $mylist $idx $idx]
puts "$mylist"

Output:
{d e f} {g h i}

This is what actually happens:

Output:
{a b c} {d e f} {g h i}

When I puts $idx, it comes out with "-1" no matter what I search. I know it's easy to remove the elements with a firm index, but I need the program to be able to search the elements of a list to remove it. Basically, how do I find the index of the element that I want to remove by only searching for one part of it?

EDIT: Nevermind. I figured out that you need to use * in your search. Since I haven't seen it anywhere else here, I'll leave my original question, and the solution I found:

set label "a"
set idx [lsearch $mylist $label*]
set mylist [lreplace $mylist $idx $idx]

Output:
{d e f} {g h i}
Community
  • 1
  • 1
Peter
  • 25
  • 2
  • 7

1 Answers1

1

Are you always looking for the search term in the first element of each sublist? If so, you can use lsearch's -index option, which specifies which part of each element is to be examined:

set mylist [list {a b c} {d e f} {g h i}]
set label "a"
set idx [lsearch -index 0 -exact $mylist $label]
set mylist [lreplace $mylist $idx $idx]
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215