How to Merge Tcl Lists and Eliminate Duplicates

The Problem

I want to merge two lists, and eliminate duplicates.

The Solution

Use the union command from the Tclx package.

49 % package require Tclx
8.4
50 % set list1 {Peter Paul Marry}
Peter Paul Marry
51 % set list2 {Paul John Ringo George}
Paul John Ringo George
52 % union $list1 $list2
George John Marry Paul Peter Ringo
53 % union {1 1 1 1 1} {2 2 2}
1 2

Discussion

  • Line 49 imports the Tclx package
  • Line 50 to 51 creates two lists which contain a common element: Paul
  • Line 52 merges these two lists using the union (as in set theory) command. The result is a merged list with no duplicates
  • Line 53 merges two lists with duplicate elements within themselves. The result is a single list in which each element only appears once.

The union command is good for merging lists while removing duplicates. The command does not guarantee the order of the elements so do not use it in situation when order matters.

4 thoughts on “How to Merge Tcl Lists and Eliminate Duplicates

  1. Kris

    Here’s a solution for those of us who are unable to use the TclX solution:

    proc union {list1 list2} {
    set newList $list1;
    foreach item $list2 {
    set newList [lappend newList $item];
    }
    return [lsort -uniq $newList];
    }

  2. Hai Post author

    Thank you Kris,
    Without Tclx, I would do something like this:


    proc union {list1 list2} {
    return [lsort -unique [concat $list1 $list2]]
    }

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