Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate elements from list in Tcl

Tags:

tcl

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.

like image 274
user2901871 Avatar asked Dec 04 '13 10:12

user2901871


People also ask

How do I remove duplicates from elements list?

To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of the set() method is that it returns distinct elements.

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.


3 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]
like image 137
m4eme Avatar answered Oct 07 '22 05:10

m4eme


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.

like image 8
glenn jackman Avatar answered Oct 07 '22 05:10

glenn jackman


glenn jackman's answer work perfectly on Tcl 8.6 and above.

For Tcl 8.4 and below (No dict command). You can use:

proc list_unique {list} {
    array set included_arr [list]
    set unique_list [list]
    foreach item $list {
        if { ![info exists included_arr($item)] } {
            set included_arr($item) ""
            lappend unique_list $item
        }
    }
    unset included_arr
    return $unique_list
}

set list   [list this that when what when how]
set unique [list_unique $list]

This will also preserve the order of the elements and this is the result:

this that when what how

like image 1
Hazem Avatar answered Oct 07 '22 04:10

Hazem