Python Language Set

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

TODO

Overview

Sets and the __hash__() Function

Sets and the __hash__() Function

Initialization

Literal initialization:

s = {1, 2, 3}

Set from a tuple:

s = set((1, 2, 3))

Set from a list:

s = set([1, 2, 3])

Set from a string:

s = set('ABC')
print(s)  # {'C', 'B', 'A'}

Shallow Copy

s = set()
s.add('a')
s2 = s.copy()

Add Elements

Add One Element

s = set()
s.add('a')
assert 'a' in s

Add Multiple Elements

Update the set with the union of itself and others, where others can be any iterable. update() eliminates duplicates.

s = set()
s.update(['a', 'b', 'a'])
assert len(s) == 2
assert 'a' in s
assert 'b' in s

Add Multiple Elements with union()

union() merges the elements of the iterable given as argument into the current set, and returns a new set, which is the union of the current set and the argument.

Remove an Element from a Set

s.remove('a')

Does not return anything, simply removes the element.

If the element does not exist, throws KeyError: 'a'.

Convert to List

s=set()
l=list(s)

Set Operations

Inclusion

Check whether a set is included in another set with issubset():

set_a = {'a', 'b', 'c', 'd'}
set_b = {'a', 'c'}
assert set_b.issubset(set_a)

The function also works for non-homogenous sets, where the elements have different types:

set_a = {'a', 'b', 'c', 1, 5, 9}
set_b = {1, 'c'}
assert set_b.issubset(set_a)

Intersection

set_a = {'a', 'b', 'c', 1, 2, 3}
set_b = {'x', 'y', 'c', 1, 10, 20}
assert set_a.intersection(set_b) == {1, 'c'}

frozenset()

The fronzenset() returns an immutable frozenset object initialized with the elements from a given iterable. frozenset objects can be used as dictionary keys.

If the iterable contains duplicate elements, they are ignored (the iterable is handled like a set):

f = frozenset(['a', 'b', 'c'])
f2 = frozenset(['a', 'b', 'c', 'a'])
assert f == f2