The Python list container can be used for many practical things. In this somewhat light-hearted introspection of modern day politics we are looking at two lists and attempt to clear out elements that shouldn't be in both lists. No offense to anyone is intended, the outcome with the sets was a surprise to me.

# the government inner circle keeps two lists of countries
# one is the yeList of countries that pretty well go along with any adventure 
# and the other list is the noList of countries that are not always with us
# let's assume these lists have gotten longer and some countries now appear in both lists
# you have to find which ones have dared to say no and remove them from the yeList
# tested with Python24          vegaseat         04jul2005

yeList = ['England','Italy','Portugal','Spain','Israel','Poland','Morocco','Japan','Danmark']
noList = ['China','Canada','Brazil','Germany','Iran','Spain','France','Russia','Turkey']

print "yeList =", yeList
print "noList  =", noList


# since the original yeList would change, we are making a copy to use
# (note, an alias like yesList = yeList has the identical address and would change too)
yesList = yeList[:]

# using try and except ...
for country in yesList:
        # if found in noList remove from yesList
        pos = noList.index(country)
        print pos, country  # test
    except ValueError:

print '-'*70
print "washed yesList =", yesList


# another way to do this, using filter() ...
yesList = yeList[:]
yesList = filter(lambda s: s not in noList, yesList)
print '-'*70
print "laundered yesList =", yesList


# yet another way to do it, using list comprehension ...
yesList = yeList[:]
yesList = [country for country in yesList if country not in noList]
print '-'*70
print "sanitary yesList =", yesList


# should one of the lists be very long, then it is efficient to convert it to a set ...
yesList = yeList[:]
noSet = set(noList)
yesList = [country for country in yesList if country not in noSet]
print '-'*70
print "immaculate yesList =", yesList


# fast algorithm, easy to comprehend, but changes the order ...
yeSet = set(yeList)
noSet = set(noList)
newyesSet = yeSet - noSet
print "the newyesSet =", newyesSet
About the Author


Python v.2.4 has sets built-in. With earlier version you have to import sets.