A set is a collection of unique items with no fixed order. Sets are used to remove duplicates, to check quickly whether a value exists, and to do maths on groups, such as finding the items two groups share. This lesson covers how to create sets, add and remove items, and use union, intersection and difference, with output for every example.

Try every example in our online Python compiler.

 

What is a set?

A set is written with curly braces {}. It stores each value only once, it has no index, and the order of its items can change. The items must be unchangeable types such as numbers, strings and tuples.

s = {1, 2, 3, 3, 2}
print(s)
print(type(s))

Output:

{1, 2, 3}
<class 'set'>

The duplicates are removed automatically.

 

Create an empty set

Empty curly braces {} create a dictionary, not a set. Use set() for an empty set.

empty = set()
print(type(empty))
print(type({}))
print(set([1, 2, 2, 3]))

Output:

<class 'set'>
<class 'dict'>
{1, 2, 3}

Add items

Use add() for one item and update() for many. Adding an item that already exists changes nothing.

Because a set has no fixed order, the examples below print sorted(s) so that the output is always the same.

s = {1, 2, 3}
s.add(4)
s.add(2)
print(sorted(s))

s.update([5, 6])
print(sorted(s))

Output:

[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]

Remove items

s = {1, 2, 3, 4, 5, 6}
s.remove(6)
s.discard(99)
print(sorted(s))

try:
    s.remove(99)
except KeyError as e:
    print('KeyError:', e)

Output:

[1, 2, 3, 4, 5]
KeyError: 99

remove() raises a KeyError if the item is missing, while discard() does nothing. pop() removes and returns an arbitrary item, and clear() empties the set.

 

Check if an item exists

print(3 in {1, 2, 3})

Output:

True

Checking a set with in is very fast, even for a large set. That is a major reason to use a set instead of a list for lookups.

 

Set operations

Set operations work like Venn diagrams. Take two sets:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

Operation

Operator

Method

Result

Union (all items from both)

a | b

a.union(b)

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

Intersection (items in both)

a & b

a.intersection(b)

{3, 4}

Difference (in a, not in b)

a – b

a.difference(b)

{1, 2}

Symmetric difference (in one, not both)

a ^ b

a.symmetric_difference(b)

{1, 2, 5, 6}

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
print(sorted(b - a))
print(sorted(a ^ b))

Output:

[1, 2, 3, 4, 5, 6]
[3, 4]
[1, 2]
[5, 6]
[1, 2, 5, 6]

Subset and superset

print({1, 2}.issubset({1, 2, 3}))
print({1, 2, 3}.issuperset({1}))
print({1, 2}.isdisjoint({3, 4}))

Output:

True
True
True

issubset() checks that all items are in the other set, issuperset() checks the reverse, and isdisjoint() checks that the two sets share nothing.

 

Remove duplicates from a list

nums = [3, 1, 2, 3, 1]
unique = sorted(set(nums))
print(unique)
print(len(nums), len(set(nums)))

Output:

[1, 2, 3]
5 3

set(nums) removes the duplicates, but the order is lost. Use sorted() if you want an ordered list.

 

Set comprehension

squares = {x * x for x in range(1, 6)}
print(sorted(squares))

Output:

[1, 4, 9, 16, 25]

Common mistakes

  • Using {} for an empty set. It creates a dictionary. Use set().
  • Expecting a fixed order. A set has no order, so do not rely on the order of items.
  • Trying to use an index. s[0] raises a TypeError, because a set has no index.
  • Putting a list inside a set. Lists cannot be changed, so they are not allowed. Use a tuple instead.

 

Practice questions

  1. Remove the duplicates from [5, 3, 5, 2, 3, 1].
  2. Find the common items of {1, 2, 3, 4} and {2, 4, 6}.
  3. Find the items in {1, 2, 3} that are not in {2, 3, 4}.
  4. Check whether the words ‘listen’ and ‘silent’ have the same letters.

 

Summary

  • A set stores unique items with no order and no index.
  • Use set() to create an empty set, and add(), update(), remove() and discard() to change it.
  • Use union, intersection, difference and symmetric difference to work with groups.
  • Use a set to remove duplicates and for fast lookups.