How to Remove Duplicates in a Tcl List

The Problem

I want to remove all duplicates within a list

The Solutions

There are at least two solutions to this problem. The first employs the lsort -unique command and the second uses the lrmdups command from the Tclx package.

56 % package require Tclx
8.4
57 % lsort {1 3 1 2 2}
1 1 2 2 3
58 % lsort -unique {1 3 1 2 2}
1 2 3
59 % lrmdups {1 3 1 2 2}
1 2 3

Discussion

  • Line 56 imports the Tclx package needed by the lrmdups command.
  • Line 57 sorts the list, but does not remove duplicates.
  • Line 58 sorts and removes duplicates. This is what we want.
  • Line 59 achives the same result as above, but more expressive. Note that the lrmdups command returns a sorted list, the same way as the lsort -unique command.

6 thoughts on “How to Remove Duplicates in a Tcl List

  1. Hai Post author

    @benroll: I agree. These are “lazy” (as in, you don’t have to code it yourself) solutions, but in order to do it right, you have to write code yourself.

  2. sairam panigrahi

    use this code for removing duplicates,it will work fi9 …..

    set listname [list a a a a b c d e f g]
    a a a a b c d e f g
    set result [lsort -unique $listname]
    a b c d e f g

  3. Navrath

    I have a file in which contents are in following order:
    This is not right
    Right statement it is
    This is incorrect
    Give right expression

    How do I find the count of the word right using tcl script? Since it is not in list I’m unable to uniquify these statements and take the expression.
    Which commands are proper to use lsort or regexp?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s