ZetCode

Python set

last modified November 18, 2026 Python 3.15

In this article we work with the Python set collection. We show how to create sets and perform operations on them.

A Python set is an unordered collection of unique elements. Sets are mutable; we can add and remove elements. They support the operations known from mathematics, such as union, intersection, and difference.

Sets are implemented as hash tables. Testing whether an element is in a set takes the same time no matter how large the set is, which makes sets the right tool for membership tests and for removing duplicates. In return, the elements must be hashable and the sets keep no particular order.

Set literal

We create a set with curly brackets; the elements are separated by commas.

set_literal.py
nums = {1, 2, 2, 2, 3, 4}

print(type(nums))
print(nums)

empty = set()
print(type(empty), empty)

print(type({}))

The example creates a set with literal notation.

nums = {1, 2, 2, 2, 3, 4}

A set contains unique elements; even though we have provided the value 2 three times, the set contains only one 2.

empty = set()
print(type(empty), empty)

print(type({}))

An empty set must be created with the set function. Empty curly brackets create an empty dictionary.

$ python set_literal.py
<class 'set'>
{1, 2, 3, 4}
<class 'set'> set()
<class 'dict'>

The set function

The set function creates a new set from the elements of an iterable, such as a list, a string, or a range.

set_fun.py
seasons = ['spring', 'summer', 'autumn', 'winter']
print(sorted(set(seasons)))

print(sorted(set('mississippi')))
print(set(range(5)))

vals = [3, 1, 3, 2, 1, 5, 2]
print(sorted(set(vals)))
print(list(dict.fromkeys(vals)))

We create sets from a list, a string, and a range. Converting a sequence to a set is the quickest way of removing duplicates. We print sorted lists of the elements so that the output is the same on every run.

print(list(dict.fromkeys(vals)))

A set does not keep the original order. If we need to remove duplicates and keep the order of the first occurrences, we use the keys of a dictionary, which keeps insertion order.

$ python set_fun.py
['autumn', 'spring', 'summer', 'winter']
['i', 'm', 'p', 's']
{0, 1, 2, 3, 4}
[1, 2, 3, 5]
[3, 1, 2, 5]

Hashable elements

Set elements must be hashable. Immutable built-in types such as numbers, strings, and tuples are hashable; lists, dictionaries, and sets are not.

hashable.py
points = {(1, 2), (3, 4), (1, 2)}
print(points)

try:
    bad = {[1, 2], [3, 4]}
except TypeError as e:
    print(e)

nums = {1, 1.0, True}
print(nums)

print(hash(1) == hash(1.0) == hash(True))

Tuples can be set elements; lists cannot. Since Python 3.14, the error message names the operation that failed; older versions print just unhashable type: 'list'.

nums = {1, 1.0, True}
print(nums)

Elements that compare equal and have the same hash are considered the same element. 1, 1.0, and True are equal, so the set keeps only the first one.

$ python hashable.py
{(1, 2), (3, 4)}
cannot use 'list' as a set element (unhashable type: 'list')
{1}
True

Iteration and order

A set can be iterated with a for loop. The order of the elements is an implementation detail and must not be relied upon.

order.py
words = {'sky', 'cup', 'forest', 'wood', 'cloud', 'water'}

for word in words:
    print(word, end=' ')

print()

for word in sorted(words):
    print(word, end=' ')

print()

for idx, word in enumerate(sorted(words), 1):
    print(f'{idx}. {word}')

For strings, the order depends on their hash values, which are randomized for each Python process. The first line of the output is likely to differ on the next run. When the order matters, we iterate over a sorted list of the elements.

$ python order.py
cloud water cup wood sky forest 
cloud cup forest sky water wood 
1. cloud
2. cup
3. forest
4. sky
5. water
6. wood

Membership testing

The in and not in operators test for the existence of an element in the set.

membership.py
words = {'spring', 'table', 'cup', 'bottle', 'coin'}

word = 'cup'

if word in words:
    print(f'{word} is present in the set')
else:
    print(f'{word} is not present in the set')

word = 'tree'

if word not in words:
    print(f'{word} is not present in the set')
else:
    print(f'{word} is present in the set')

We check if two words are present in the set with the membership operators. For a list, the in operator compares the element with every item; for a set, it computes the hash and looks at a single slot of the table.

$ python membership.py
cup is present in the set
tree is not present in the set

Built-in functions

Built-in functions that work with iterables, such as len, min, max, sum, sorted, any, and all, accept sets too.

builtins.py
nums = {21, 11, 42, 29, 22, 71, 18}

print(f'Number of elements: {len(nums)}')
print(f'Minimum: {min(nums)}')
print(f'Maximum: {max(nums)}')
print(f'Sum: {sum(nums)}')

print(f'Sorted: {sorted(nums)}')
print(f'Sorted desc: {sorted(nums, reverse=True)}')

print(any(n > 70 for n in nums))
print(all(n > 10 for n in nums))

We apply several built-in functions to a set of integers. The sorted function returns a new sorted list from the set's elements.

$ python builtins.py
Number of elements: 7
Minimum: 11
Maximum: 71
Sum: 214
Sorted: [11, 18, 21, 22, 29, 42, 71]
Sorted desc: [71, 42, 29, 22, 21, 18, 11]
True
True

Adding elements

The add method adds a single element; the update method adds the elements of one or more iterables.

add_update.py
words = {'spring', 'table', 'cup'}

words.add('coin')
words.add('cup')
print(sorted(words))

words.update(['tree', 'sky'], ('cup', 'pen'), 'ab')
print(sorted(words))

words |= {'river', 'lake'}
print(len(words))

Adding an element that is already present has no effect.

words.update(['tree', 'sky'], ('cup', 'pen'), 'ab')

The update method takes any number of iterables. A string is an iterable of characters, so 'ab' adds two elements, a and b, not the word ab. To add a single string, we use add.

words |= {'river', 'lake'}

The |= operator is the in-place form of union; it works like update but requires a set on the right side.

$ python add_update.py
['coin', 'cup', 'spring', 'table']
['a', 'b', 'coin', 'cup', 'pen', 'sky', 'spring', 'table', 'tree']
11

Removing elements

The remove method removes an element and raises KeyError if the element is missing. The discard method does nothing in that case. The pop method removes and returns an arbitrary element, and clear removes all elements.

remove.py
words = {'spring', 'table', 'cup', 'bottle', 'coin', 'cloud'}

words.discard('coin')
words.discard('pen')

words.remove('cup')

try:
    words.remove('cup')
except KeyError as e:
    print(f'KeyError: {e}')

print(sorted(words))

word = words.pop()
print(f'popped {word!r}, {len(words)} left')

words.clear()
print(words)

try:
    words.pop()
except KeyError as e:
    print(f'KeyError: {e}')

Discarding a missing element is silent; removing it twice raises a KeyError. Which element pop returns is not specified, so the popped word may differ between runs. Popping from an empty set raises a KeyError.

$ python remove.py
KeyError: 'cup'
['bottle', 'cloud', 'spring', 'table']
popped 'spring', 3 left
set()
KeyError: 'pop from an empty set'

Set operations

Sets support union, intersection, difference, and symmetric difference.

operations.py
set1 = {'a', 'b', 'c', 'd', 'e'}
set2 = {'a', 'b', 'x', 'y', 'z'}

print('Set 1:', sorted(set1))
print('Set 2:', sorted(set2))

print('intersection:', sorted(set1.intersection(set2)))
print('union:', sorted(set1.union(set2)))
print('difference:', sorted(set1.difference(set2)))
print('symmetric difference:', sorted(set1.symmetric_difference(set2)))

The example shows the four set operations as methods.

print('intersection:', sorted(set1.intersection(set2)))

The intersection method returns the elements that are in both set1 and set2.

print('union:', sorted(set1.union(set2)))

The union method returns all elements from both sets.

print('difference:', sorted(set1.difference(set2)))

The difference method returns the elements that are in set1 but not in set2.

print('symmetric difference:', sorted(set1.symmetric_difference(set2)))

The symmetric_difference method returns the elements that are in set1 or set2, but not in both.

$ python operations.py
Set 1: ['a', 'b', 'c', 'd', 'e']
Set 2: ['a', 'b', 'x', 'y', 'z']
intersection: ['a', 'b']
union: ['a', 'b', 'c', 'd', 'e', 'x', 'y', 'z']
difference: ['c', 'd', 'e']
symmetric difference: ['c', 'd', 'e', 'x', 'y', 'z']

Set operators

The same operations are available as the &, |, -, and ^ operators.

operators.py
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7}
set3 = {5, 7, 9}

print(set1 & set2)
print(set1 | set2)
print(set1 - set2)
print(set1 ^ set2)

print(set1 & set2 & set3)
print(set1.union(set2, set3))

print(set1.union([10, 11]))

try:
    print(set1 | [10, 11])
except TypeError as e:
    print(e)

Small integers hash to themselves, so sets of small integers usually print in ascending order; this is still an implementation detail.

print(set1 & set2 & set3)
print(set1.union(set2, set3))

Operators can be chained, and the methods accept several arguments.

print(set1.union([10, 11]))

There is a difference between the two forms: the methods accept any iterable, while the operators require both operands to be sets. Using | with a list raises a TypeError.

$ python operators.py
{4, 5}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3}
{1, 2, 3, 6, 7}
{5}
{1, 2, 3, 4, 5, 6, 7, 9}
{1, 2, 3, 4, 5, 10, 11}
unsupported operand type(s) for |: 'set' and 'list'

In-place operations

The augmented assignment operators &=, |=, -=, and ^= modify the set in place. They have method counterparts: intersection_update, update, difference_update, and symmetric_difference_update.

in_place.py
stock = {'apples', 'pears', 'plums', 'kiwis'}

stock -= {'plums'}
print(sorted(stock))

stock &= {'apples', 'kiwis', 'oranges'}
print(sorted(stock))

stock ^= {'kiwis', 'lemons'}
print(sorted(stock))

stock.difference_update(['apples'])
print(sorted(stock))

We remove plums, keep only the items also found in the second set, toggle kiwis and lemons, and finally remove apples with a method, which accepts a list.

$ python in_place.py
['apples', 'kiwis', 'pears']
['apples', 'kiwis']
['apples', 'lemons']
['lemons']

Subsets and supersets

If all elements of set A are contained in set B, A is a subset of B and B is a superset of A. Two sets are disjoint if they have no common elements.

subset_superset.py
set1 = {'a', 'b', 'c', 'd', 'e'}
set2 = {'a', 'b', 'c'}
set3 = {'x', 'y', 'z'}

print(set2.issubset(set1))
print(set2 <= set1)
print(set2 < set1)
print(set1 < set1)

print(set1.issuperset(set2))
print(set1 >= set2)

print(set2.isdisjoint(set3))
print(set1.isdisjoint(set2))

print({1, 2} == {2, 1})

The issubset and issuperset methods have the <= and >= operator forms. The < and > operators test for a proper subset or superset, which must not be equal to the other set; that is why set1 < set1 is false. The isdisjoint method checks that the sets have no element in common. Two sets are equal if they have the same elements, regardless of order.

$ python subset_superset.py
True
True
True
False
True
True
True
False
True

Set comprehension

A set comprehension creates a set from an iterable in a single expression. It uses curly brackets.

comprehension.py
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

squares = {e * e for e in nums if e % 2 == 0}
print(sorted(squares))

words = ['Sky', 'sky', 'SKY', 'cloud', 'Cloud', 'rain']
print(sorted({w.lower() for w in words}))

lengths = {len(w) for w in words}
print(lengths)

We create a set of squares of even numbers, a set of words in lowercase, and a set of word lengths. Duplicates produced by the expression are dropped.

$ python comprehension.py
[4, 16, 36, 64, 100]
['cloud', 'rain', 'sky']
{3, 4, 5}

Frozenset

A frozenset is an immutable version of a set. It supports the same queries and operations, but no methods that modify it. Because it is immutable, it is hashable and can be an element of another set or a dictionary key.

frozen.py
fs = frozenset([1, 2, 3, 2])
print(fs)

try:
    fs.add(4)
except AttributeError as e:
    print(e)

print(fs | {4, 5})

groups = {frozenset({'a', 'b'}), frozenset({'c'})}
print(frozenset({'b', 'a'}) in groups)

distances = {frozenset({'Bratislava', 'Vienna'}): 79,
             frozenset({'Bratislava', 'Budapest'}): 200}
print(distances[frozenset({'Vienna', 'Bratislava'})])

A frozenset has no add method. Operations with frozensets return new frozensets.

distances = {frozenset({'Bratislava', 'Vienna'}): 79,
             frozenset({'Bratislava', 'Budapest'}): 200}
print(distances[frozenset({'Vienna', 'Bratislava'})])

A frozenset makes a good key for unordered pairs: the distance between two cities does not depend on the order in which we name them.

$ python frozen.py
frozenset({1, 2, 3})
'frozenset' object has no attribute 'add'
frozenset({1, 2, 3, 4, 5})
True
79

Comparing two lists

Set operations are handy for comparing collections.

compare_lists.py
expected = ['John', 'Paul', 'Lucy', 'Anna', 'Peter']
present = ['Lucy', 'John', 'Robert', 'Anna']

exp, pres = set(expected), set(present)

print('missing:', sorted(exp - pres))
print('unexpected:', sorted(pres - exp))
print('both:', sorted(exp & pres))

We compare the expected and present people. The difference gives the missing and unexpected names, the intersection those who are in both lists.

$ python compare_lists.py
missing: ['Paul', 'Peter']
unexpected: ['Robert']
both: ['Anna', 'John', 'Lucy']

Unique words

In the following example, we count the unique words in a text.

unique_words.py
import re

text = '''The Battle of Thermopylae was fought between an alliance of Greek
city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I
over the course of three days, during the second Persian invasion of Greece.'''

words = re.findall(r"[\w-]+", text.lower())

print(len(words))

unique = set(words)
print(len(unique))

repeated = {w for w in unique if words.count(w) > 1}
print(sorted(repeated))

We extract the words in lowercase with re.findall; the pattern allows hyphens, so city-states is one word. The length of the set is the number of unique words. A set comprehension then picks the words that occur more than once.

$ python unique_words.py
38
29
['of', 'persian', 'the']

Modifying a set during iteration

A set must not change its size while we iterate over it.

modify_loop.py
nums = {1, 2, 3, 4, 5, 6}

try:
    for n in nums:
        if n % 2 == 0:
            nums.discard(n)
except RuntimeError as e:
    print(e)

nums = {1, 2, 3, 4, 5, 6}

for n in set(nums):
    if n % 2 == 0:
        nums.discard(n)

print(nums)

nums = {1, 2, 3, 4, 5, 6}
nums = {n for n in nums if n % 2 != 0}
print(nums)

Removing elements inside the loop raises a RuntimeError. We iterate over a copy instead, or, better, build a new set with a set comprehension.

$ python modify_loop.py
Set changed size during iteration
{1, 3, 5}
{1, 3, 5}

Source

Set types – Python documentation

In this article we have worked with the Python set collection. See also Python dictionary, Python list, Python list comprehensions, and Python collections.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.