Python Glossary Русский

all Python 3Sets (set)term

Creating a set

creation

A set is written as a {1, 2} literal or built with set() or frozenset(); an empty one only with set(). Duplicates are removed. The order is not guaranteed.

Syntax

{a, b}  |  set(iterable)  |  frozenset(iterable)

An empty set can only be made with set(); bare {} gives an empty dict. Elements must be hashable, so a list cannot go in (a tuple can), and a plain set cannot be an element of another set — that is what the immutable frozenset is for. Watch out for set('abc') too: it splits the string into individual characters rather than storing it whole.

Examples

s = {1, 2, 3}
# → {1, 2, 3}
s2 = set([1, 2, 2, 3, 3])
print(s2)
# → {1, 2, 3} (дубли удалены)
s3 = set('hello')
print(sorted(s3))
# → ['e', 'h', 'l', 'o'] (порядок элементов множества не определён, поэтому сортируем)
empty = set()
print(type(empty))
# → <class 'set'> ({} — это dict!)
fs = frozenset([1, 2, 3])
print(fs)
# → frozenset({1, 2, 3})
nums = [1, 1, 2, 2, 3]
unique = list(set(nums))
print(sorted(unique))
# → [1, 2, 3]
s4 = {x**2 for x in range(5)}
print(sorted(s4))
# → [0, 1, 4, 9, 16]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy