Python Glossary Русский

all Python 3Sets (set)function

set.difference

set theory

Return a new set of elements not in the others (difference). Operator: -.

Syntax

s.difference(*others)

The method accepts any iterables — a list, a string, a generator — while the - operator only works between two sets and raises TypeError on anything else. Difference is not symmetric: swap the operands and you get a different answer. The original set is left untouched; use difference_update() when you want to shrink it in place.

Examples

print(sorted({1, 2, 3}.difference({2, 3})))   # → [1]
print(sorted({1, 2, 3, 4}.difference({2}, [3])))   # → [1, 4]
print(sorted({1, 2, 3} - {3}))   # → [1, 2]
print(sorted({1, 2, 3}.difference({3, 4})), sorted({3, 4}.difference({1, 2, 3})))   # → [1, 2] [4]
print(sorted({1, 2}.difference({1, 2, 3})))   # → []
print({1, 2, 3} - [3])   # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy