Next / Previous / Contents / TCC Help System / NM Tech homepage

15.2. Operations on mutable sets

The operations described in this section apply to set (mutable) values, but may not be used with frozenset (immutable) values.

S.add(x)

Add element x to set S. Duplicate elements will be ignored.

>>> pbr=set(['USA', 'Brazil', 'Canada'])
>>> pbr.add('Australia')
>>> pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])
>>> pbr.add('USA')
>>> pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])

S.clear()

Remove all the elements from set S.

>>> pbr
set(['Brazil', 'USA'])
>>> pbr.clear()
>>> pbr
set([])

S.discard(x)

If set S contains element x, remove that element from S.

If x is not in S, it is not considered an error; compare S.remove(x).

>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.discard('Swaziland')
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.discard('Australia')
>>> pbr
set(['Brazil', 'USA'])

S1.difference_update(S2)

Modify set S1 by removing any values found in S2. Value S2 may be a set or a sequence.

>>> s1=set('roygbiv')
>>> s1.difference_update('rgb')
>>> s1
set(['i', 'o', 'v', 'y'])

S1 -= S2

Same as S1.difference_update(S2), but S2 must be a set.

S1.intersection_update(S2)

Modify set S1 so that it contains only values found in both S1 and S2.

>>> s1=set('roygbiv')
>>> s1
set(['b', 'g', 'i', 'o', 'r', 'v', 'y'])
>>> s1.intersection_update('roy')
>>> s1
set(['y', 'r', 'o'])

S1 &= S2

Same as S1.intersection_update(S2), but S2 must be a set.

S.remove(x)

If element x is in set S, remove that element from S.

If x is not an element of S, this operation will raise a KeyError exception.

>>> pbr
set(['Brazil', 'Canada', 'Australia', 'USA'])
>>> pbr.remove('Canada')
>>> pbr
set(['Brazil', 'Australia', 'USA'])
>>> pbr.remove('Swaziland')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Swaziland'

S1.symmetric_difference_update(S2)

Remove from S1 any elements found in both S1 and S2. Value S2 may be a set or a sequence.

>>> s1=set('abcd')
>>> s1.symmetric_difference_update('cdefg')
>>> s1
set(['a', 'b', 'e', 'g', 'f'])

S1 ^= S2

Same as S1.symmetric_difference_update(S2), but S2 must be a set.

S1.update(S2)

Add to S1 any elements of S2 not found in S1. The S2 argument may be a set or a sequence.

>>> s1=set('rgb')
>>> s1
set(['r', 'b', 'g'])
>>> s1.update('roygbiv')
>>> s1
set(['b', 'g', 'i', 'o', 'r', 'v', 'y'])

S1 |= S2

Same as S1.update(S2), but S2 must be a set.