Python Glossary Русский

all Python 3Sets (set)term

Practical set problems

practice

Typical uses: unique items, intersections, differences and fast membership tests.

Syntax

set(lst)  |  a & b  |  a - b  |  a ^ b

Turning a list into a set drops the order along with the duplicates; when you need the unique values in their original order, use list(dict.fromkeys(lst)) instead. The real win is that x in s costs constant time while scanning a list is linear, so convert once before running many membership tests. Only hashable objects fit inside, which rules out lists and dicts as elements.

Examples

lst = [1, 2, 2, 3, 3, 3, 4]
unique = sorted(set(lst))
print(unique)
# → [1, 2, 3, 4]
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
common = set(a) & set(b)
print(common)
# → {3, 4}
only_a = set(a) - set(b)
print(only_a)
# → {1, 2}
print(len(set(lst)))
# → 4 (число уникальных)
has_dup = len(lst) != len(set(lst))
print(has_dup)
# → True (есть дубликаты)
tags1 = {'python', 'data', 'ml'}
tags2 = {'java', 'data', 'web'}
print(sorted(tags1.symmetric_difference(tags2)))
# → ['java', 'ml', 'python', 'web'] (у множества строк порядок не определён, поэтому сортируем)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy