Beginner   Chapter 49 · 25 min read · Module 4: Python Data Structures

Introduction to Sets

Learning objectives
  • After this chapter you can create sets with braces and with set().
  • You can explain that sets hold only unique items and have no order or index.
  • You can remove duplicates from a list using a set.
  • You can test membership with in and loop over a set.
  • You can use union, intersection, difference and symmetric difference operators.

A set is a collection that keeps only one copy of each value. If you add the same value twice, the set still holds it once. A set does not remember the order in which you added items, and you cannot ask for the item at position 0.

Sets are useful when you care about which values exist, not how many times they appear or in which order. Typical jobs are removing duplicates, checking if a value is present very quickly, and comparing two groups to see what they share.

In this chapter you will learn how to create sets, what values can be stored, and how the operators for union, intersection and difference work. The next chapter covers the set methods in detail.

Creating a set

Use curly braces with items separated by commas: {1, 2, 3}. To make an empty set you must write set(), because {} creates an empty dictionary. You can also build a set from any iterable, such as a list, a string or a range, by passing it to set().

Set: a mutable, unordered collection of unique, hashable items.
Example 1: ways to create a set
a = {3, 1, 2, 3, 1}
print(len(a))
print(sorted(a))
b = set([5, 5, 6])
print(sorted(b))
letters = set("hello")
print(sorted(letters))
empty = set()
print(len(empty), type({}).__name__)
3 [1, 2, 3] [5, 6] ['e', 'h', 'l', 'o'] 0 dict
We print sorted(...) in these examples because the order in which a set shows its items is not something you should rely on. Strings in particular may appear in a different order each time you run a program.

What can go inside a set

Set items must be hashable. In simple words, this means the value cannot change in a way that would affect its identity. Numbers, strings, booleans and tuples of such values are fine. Lists, dictionaries and other sets are not allowed, and trying to add one raises TypeError. A set itself can change, so you may add and remove items.

Be careful with values that are equal: 1, 1.0 and True are all equal and have the same hash, so a set keeps only the first one that was added.

Example 2: hashable and unhashable items
ok = {1, "one", (1, 2), 2.5}
print(len(ok))
try:
    bad = {1, [2, 3]}
except TypeError as e:
    print("TypeError:", e)
print(len({1, 1.0, True}))
4 TypeError: unhashable type: 'list' 1

Sets have no order and no index

You cannot write s[0] on a set, and you cannot slice it. You can loop over it with for, but the order of items is decided by Python, so do not depend on it. If you need a predictable order, use sorted(s), which returns a list.

Removing duplicates

The simplest way to remove duplicates is set(items). If you also need to keep the original order, use dict.fromkeys(items) instead, because dictionaries remember the order of insertion; then wrap it with list().

Example 3: unique values
nums = [4, 1, 4, 2, 1, 3]
print(sorted(set(nums)))
print(list(dict.fromkeys(nums)))
print(len(nums), len(set(nums)))
[1, 2, 3, 4] [4, 1, 2, 3] 6 4

Duplicates are removed silently. No error is raised when you write the same value twice, and the set simply keeps one copy. This is exactly what you want when you collect values such as the cities in a customer list, where you care only about which cities appear and not how many times.

Two sets are equal when they hold the same items, whatever the order in which they were written. So {1, 2, 3} == {3, 2, 1} is True. This is different from lists, where the order is part of the value.

Fast membership test

Checking x in s for a set is very fast, even for a million items, because the set uses hashing. For a list, Python must compare against the items one by one. If you test membership many times, convert the list to a set first.

Example 4: membership and looping
allowed = {"red", "green", "blue"}
print("red" in allowed)
print("pink" in allowed)
print("pink" not in allowed)
total = 0
for n in {10, 20, 30}:
    total += n
print(total)
True False True 60

Set operators

Sets follow the rules of mathematical sets. The four main operators each build a new set.

OperatorMeaningFor a={1,2,3}, b={3,4}
a | bunion: items in either{1, 2, 3, 4}
a & bintersection: items in both{3}
a - bdifference: in a but not b{1, 2}
a ^ bsymmetric difference: in one only{1, 2, 4}
a <= bsubset testFalse
Example 5: comparing two groups
python_club = {"Asha", "Ravi", "Mina"}
chess_club = {"Ravi", "Tom"}
print(sorted(python_club | chess_club))
print(sorted(python_club & chess_club))
print(sorted(python_club - chess_club))
print(sorted(python_club ^ chess_club))
print({1, 2} <= {1, 2, 3}, {1, 2, 3} <= {1, 2})
print({1, 2}.isdisjoint({3, 4}))
['Asha', 'Mina', 'Ravi', 'Tom'] ['Ravi'] ['Asha', 'Mina'] ['Asha', 'Mina', 'Tom'] True False True

A set is a good fit when uniqueness matters. If you need order or duplicates, use a list. If you need an unchangeable set, for example as a dictionary key, use a frozenset. Remember, sets are mutable, so they cannot be placed inside other sets, but a frozenset can.

Python syntax

Syntax
s = {1, 2, 3}
Syntax
s = set(iterable)
Syntax
empty = set()
Syntax
x in s
Syntax
a | b, a & b, a - b, a ^ b
Syntax
len(s)

Real-world applications

  • Removing duplicate entries from user data.
  • Finding common friends or tags between two groups.
  • Fast lookups in a list of banned or allowed words.
  • Finding which items are missing from a list by using difference.

Common mistakes

Mistake: Writing {} and expecting an empty set.
Fix: Use set(). Empty braces make a dictionary.
Mistake: Indexing a set such as s[0].
Fix: Sets have no order. Convert to a sorted list or loop over the items.
Mistake: Putting a list inside a set.
Fix: Use a tuple instead, because tuples of hashable values are hashable.
Mistake: Depending on the printed order of a set.
Fix: Use sorted(s) when you need a stable order.

Important tips

  • Use set(list) to count unique values with len().
  • Convert a big list to a set before many in tests.
  • Use dict.fromkeys(items) to remove duplicates and keep order.

Key points summary

  • Sets are unordered and hold unique, hashable items.
  • Empty set is set(), not {}.
  • in is very fast on sets.
  • | & - ^ give union, intersection, difference and symmetric difference.
  • Sets cannot be indexed or sliced.

Exam and interview points

  • {} is a dictionary; set() is an empty set.
  • Set items must be hashable.
  • Sets are mutable but have no indexing.
  • Union |, intersection &, difference -, symmetric difference ^.

Quick revision

  • Unique, unordered, hashable.
  • set(list) removes duplicates.
  • in is fast.
  • Operators: | & - ^.

Frequently asked questions

Why does printing a set sometimes show a different order?

The order depends on hash values and how the set was built. For strings it can change between runs. Use sorted() for a stable view.

Can a set contain a tuple?

Yes, if all items in the tuple are hashable. (1, 2) is fine but (1, [2]) is not.

How is a set different from a list?

A list keeps order and allows duplicates and indexing. A set drops duplicates, has no order and tests membership faster.

What is a frozenset?

An immutable set. It can be used as a dictionary key or as an item in another set.

Practise this chapter

23 practice questions Take the chapter quiz

Related chapters