Python Glossary Русский

all Python 3Sets (set)term

Set operations: | & - ^

operators

| — union, & — intersection, - — difference, ^ — symmetric difference. |=, &=, -= and ^= change the set in place.

Syntax

a | b  |  a & b  |  a - b  |  a ^ b

The operators demand a set (or frozenset) on both sides — a list or a string on the right raises TypeError, whereas the named forms union(), intersection() and difference() accept any iterable. Difference is not symmetric, so swapping the operands changes the answer, while ^ keeps exactly those elements that belong to one set only.

Examples

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)
# → {1, 2, 3, 4, 5, 6}
print(a & b)
# → {3, 4}
print(a - b)
# → {1, 2}
print(b - a)
# → {5, 6}
print(a ^ b)
# → {1, 2, 5, 6}
c = {1, 2}
c |= {3, 4}
print(c)
# → {1, 2, 3, 4}
d = {1, 2, 3}
d &= {2, 3, 4}
print(d)
# → {2, 3}
print({1, 2} ^ {2, 3})
# → {1, 3}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy