# Re: Standard ways to get union, intersection, difference of lists?

Discussion in 'Python' started by Gerrit Holl, Jun 26, 2003.

1. ### Gerrit HollGuest

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
>>> 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'])

http://www.python.org/dev/doc/devel/lib/module-sets.html
http://www.python.org/peps/pep-0218.html

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/

Gerrit Holl, Jun 26, 2003