Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 149 ยท Data Structures

Sets

Learn Python sets for storing unique values. Remove duplicates, test membership fast, and combine collections with union, intersection, difference and frozenset.

A set is an unordered collection of unique values. Put the same value into a set twice and it's stored only once. That one rule makes sets the natural tool for questions like "which different tags were used?", "has this visitor been seen before?" or "which students took both courses?".

Sets come straight from math, and Python gives them the operations you might remember from school: union, intersection and difference. They're also built for speed. Checking whether a value is in a set takes about the same time whether the set holds ten items or ten million. In this lesson you'll create sets, add and remove items, combine them and meet their frozen cousin, frozenset.

Creating a set

Write a set with curly braces and commas, or pass any iterable to set():

Python Making sets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the order of the printed items: it's not the order you typed, and for strings it can even change from one run to the next. Never rely on the order of a set. Sets don't keep insertion order and don't support indexing, so colors[0] raises a TypeError.

Warning: {} creates an empty dictionary, not an empty set. Always write set() when you need an empty set.

What can go in a set

Set members must be hashable, which in practice means immutable: numbers, strings, booleans, None and tuples of those. Lists, dictionaries and other sets can't be members, because they could change after being stored.

Python
ok = {1, "two", (3, 4)}
bad = {[1, 2]}            # TypeError: a list is unhashable

Mixed types in one set

A set is heterogeneous: its members don't have to share a type, as long as each one is hashable. Numbers, strings, tuples and None can live side by side. One detail catches people out: values that compare equal count as the same member, so 1, 1.0 and True collapse into a single entry.

Python Mixed and equal-looking members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Removing duplicates

The most common everyday use of a set is throwing away duplicates:

Python Unique values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

sorted() accepts a set and returns a sorted list. If the first-seen order matters, dict.fromkeys() is the idiomatic trick, because dictionaries do remember insertion order and their keys are unique too.

Membership tests

The in operator works on lists, but a list has to check its items one by one. A set jumps straight to the answer using the value's hash. For a handful of items the difference doesn't matter; for big collections checked inside a loop, it's dramatic.

Python Fast lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When you find yourself writing if item in some_list inside a loop over thousands of items, converting some_list to a set once, before the loop, is often the easiest speedup available.

The trade-off is that sets lose order and duplicates, and they use more memory than a list of the same items. If you need to know where something is, or how many times it appears, keep the list (or use a dictionary of counts). If you only need to know whether something is there, a set is the right tool.

Adding and removing items

Sets are mutable. These methods change a set in place:

Method What it does
add(x) Adds x (does nothing if it's already there)
update(iterable) Adds every item from the iterable
remove(x) Removes x; raises KeyError if it's missing
discard(x) Removes x if present; never raises
pop() Removes and returns an arbitrary item
clear() Removes everything
Python Changing a set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pick discard() when "already gone" is fine, and remove() when a missing item means something went wrong and you want to hear about it.

Set operations

This is where sets shine. Each operation has an operator and a method:

Operation Operator Method Result
Union a | b a.union(b) everything in either set
Intersection a & b a.intersection(b) only what's in both
Difference a - b a.difference(b) in a but not in b
Symmetric difference a ^ b a.symmetric_difference(b) in exactly one of them
Python Union, intersection, difference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The difference between operators and methods is small but useful: operators require both sides to be sets, while methods accept any iterable, such as a list or a string.

Each operation also has an in-place form that updates the left set instead of creating a new one: a |= b, a &= b, a -= b and a ^= b (or the methods update(), intersection_update(), difference_update() and symmetric_difference_update()).

Comparing sets

Sets can also answer "is one inside the other?":

Python Subsets and supersets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The subset check is a neat way to validate input: if required <= submitted is False, then required - submitted tells you exactly which fields are missing.

frozenset: an immutable set

A frozenset is a set that can't change after it's created. It supports every non-modifying operation (membership, union, intersection and so on), but has no add(), remove() or other mutating methods. Because it's immutable, it's hashable, so it can be a dictionary key or a member of another set:

Python frozenset

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

That last example shows a handy pattern: since {"Ana", "Ben"} and {"Ben", "Ana"} are equal sets, frozensets let you store unordered pairs without duplicates.

Note: You can also build sets with a short expression like {word.lower() for word in words}. That's a set comprehension, covered in Dictionary and Set Comprehensions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does len({1, 2, 2, 3, 3, 3}) return?

    A set keeps only unique values, so it holds 1, 2 and 3.
  2. 2. Which line creates an empty set?

    {} is an empty dictionary, [] an empty list and () an empty tuple. Only set() makes an empty set.
  3. 3. With a = {1, 2, 3} and b = {2, 3, 4}, what is a - b?

    Difference keeps items in a that aren't in b. {1, 4} would be the symmetric difference, a ^ b.
  4. 4. Which method removes an item without raising an error if it's missing?

    discard() silently does nothing for a missing item. remove() raises KeyError, and sets have no delete() method.
  5. 5. Why would you use a frozenset instead of a set?

    A frozenset can't change, which makes it hashable. It doesn't sort items or allow duplicates.

Summary

  • A set stores unique, hashable values with no order and no indexing.
  • Create one with {1, 2, 3} or set(iterable); an empty set is set(), never {}.
  • Sets remove duplicates and make in checks fast, even for huge collections.
  • Change sets with add(), update(), remove(), discard(), pop() and clear().
  • Combine sets with | (union), & (intersection), - (difference) and ^ (symmetric difference); compare them with <=, >= and isdisjoint().
  • A frozenset is an immutable, hashable set.

Next: Dictionaries, where you'll map keys to values, Python's most useful data structure.