First page Back Continue Last page Overview Graphics
Operations and Methods on Sets
Various operations can be executed on sets:
>>> A = set((3,78,43,2,9))
>>> B = set((2,89,7,9,78))
- membership testing:
>>> 78 in A
- discard(): remove an element from a set, if it is member, if not do nothing:
>>> A.discard(43)
- remove() functions like “discard” but “KeyError”, if element is not included
Return the intersection of two sets as a new set:
>>> A.intersection(B)
{9, 2, 78}
alternatively:
>>> A & B
{9, 2, 78}
- union, i.e. set.union() or “|”
- difference, i.e. set.difference() or “-”
- symmetric difference, i.e. set.symmetric_difference() or “^”
the symmetric difference are all elements which are in exactly one of the sets.
- pop() removes and returns an arbitrary element from s; raises KeyError if empty
- clear() removes all elements from set s