Standard ways to get union, intersection, difference of lists?

Gerrit Holl gerrit at
Thu Jun 26 11:29:10 CEST 2003

Mickel Grönroos wrote:
> Are there any standard list methods for getting the intersection and
> difference of two lists? (The union is easy ("list1.extend(list2)"),
> unless you want it to contain unique values.)

You want to use Sets, introduces in Python 2.3: says:
>>> from sets import Set
>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
>>> management = Set(['Jane', 'Jack', 'Susan', 'Zack'])
>>> employees = engineers | programmers | management           # union
>>> engineering_management = engineers & programmers           # intersection
>>> fulltime_management = management - engineers - programmers # difference
>>> engineers.add('Marvin')                                    # add element
>>> print engineers
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
>>> employees.issuperset(engineers)           # superset test
>>> employees.update(engineers)               # update from another set
>>> employees.issuperset(engineers)
>>> for group in [engineers, programmers, management, employees]:
...     group.discard('Susan')                # unconditionally remove element
...     print group
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
Set(['Janice', 'Jack', 'Sam'])
Set(['Jane', 'Zack', 'Jack'])
Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])

See also:


131. If a man bring a charge against one's wife, but she is not
surprised with another man, she must take an oath and then may return to
her house.
        -- 1780 BC, Hammurabi, Code of Law
Asperger Syndroom - een persoonlijke benadering:
Het zijn tijden om je zelf met politiek te bemoeien:

More information about the Python-list mailing list