Remove duplicate elements from list in Tcl

Viewed 28231

How to remove duplicate element from Tcl list say:

list is like [this,that,when,what,when,how]

I have Googled and have found lsort unique but same is not working for me. I want to remove when from list.

4 Answers

The following works for me

set myList [list this that when what when how]
lsort -unique $myList

this returns

how that this what when

which you could store in a new list

set uniqueList [lsort -unique $myList]

You could also use an dictionary, where the keys must be unique:

set l {this that when what when how}
foreach element $l {dict set tmp $element 1}
set unique [dict keys $tmp]
puts $unique
this that when what how

That will preserve the order of the elements.

Related