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:
- 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)
- Line 64: We use lindex to retrieve the the list first list
- Line 65: Assign that to the original list
We are interested in the first list in this case.
Of course, we can use intersect3 not only to remove one element, but several from a list.