ruk·si

🐍 Python
Sets

Updated at 2018-06-09 17:26

Set is a mutable collection of unique items. They are much more efficient than lists as long as the data fits in RAM.

from typing import Set

vowels: Set[str] = {'a', 'e', 'i', 'o', 'u'}
assert 'e' in vowels
assert 'x' not in vowels
assert len(vowels) == 5

name: Set[str] = set('alice')
assert name.intersection(vowels) == {'a', 'e', 'i'}
assert name.difference(vowels) == {'l', 'c'}
assert name.issubset({'a', 'l', 'i', 'c', 'e', 'x'})
assert {'a', 'l', 'i', 'c', 'e', 'x'}.issuperset(name)
assert name.union(vowels) == {'c', 'l', 'o', 'e', 'a', 'i', 'u'}

vowels.add('x')
assert 'x' in vowels
assert len(vowels) == 6

vowels.add('a')
assert len(vowels) == 6

Sets are a natural choice when your code has a lot of item in items checks.

Frozen set is an immutable collection of unique items.

consonants = frozenset({'b', 'c', 'd', 'f'})
# consonants.add('g') # => AttributeError

Counter is a mutable collection of unique items with counts.

from collections import Counter

inventory = Counter()
inventory.update({'sword': 3, 'shield': 1})
inventory.update({'helmet': 2, 'shield': 1})
assert len(inventory) == 3
assert sum(inventory.values()) == 7

You can do set operations with sets. Surprised?

one = {1, 2, 3}
two = {2, 3, 4}
assert one & two == {2, 3}
assert one | two == {1, 2, 3, 4}
assert one - two == {1}
assert two - one == {4}

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho