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

Gerrit Holl gerrit at nl.linux.org
Thu Jun 26 05:29:10 EDT 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:

http://www.python.org/dev/doc/devel/lib/set-example.html 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
False
>>> employees.update(engineers)               # update from another set
>>> employees.issuperset(engineers)
True
>>> 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:

http://www.python.org/dev/doc/devel/lib/module-sets.html
http://www.python.org/peps/pep-0218.html
http://groups.google.nl/groups?hl=nl&lr=&ie=UTF-8&oe=UTF-8&selm=mailman.1047685104.28080.python-list%40python.org

yours,
Gerrit.

-- 
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:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list