Removing Elements from a List with the TclX intersect3 Command

Recently, I needed a quick way to remove an element from a list. For example, given the following list:

set li [list a b c d e f]

How do I remove item d from it? I can use list replace, but that would be messy because I need to know the index location of the element, and the replace syntax is not easy to remember. A few minutes after I posted my question to comp.lang.tcl, someone posted a simple solution of using the TclX’s intersect3 command. Let’s take a look at the step-by-step process:
remove element from a list
Discussion:

  • Line 61: Create the list
  • Line 62: Import the Tclx package
  • Line 63: The intersect3 command takes two lists (say, listA and listB) and returns a list of three items.
    • The first is a list of items that are unique to the first list (listA)
    • the second is a list of items that are common to both
    • Finally, the third contains a list of items that are unique to the second list (listB)
  • We are interested in the first list in this case.

  • Line 64: We use lindex to retrieve the the list first list
  • Line 65: Assign that to the original list

Of course, we can use intersect3 not only to remove one element, but several from a list.

2 thoughts on “Removing Elements from a List with the TclX intersect3 Command

  1. abhishek bahuguna

    intersect3 is not the correct option to remove a particular element from the list .
    It will not only remove the “d” , but it will remove other repeated elements from the list as well , even though we want them to remove or not .
    As after using intersect3 first list will be unique.

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