Vinay Garg Assistant Professor

Lesson 20: Sets: unique values and set operations

A set keeps values with no duplicates and no order. That makes it the fastest way to remove repeats from a list and the natural tool for comparing two groups: what is shared, what is only in one.

A dark code window showing union, intersection and difference of two sets

In short

  • A set is written with curly brackets of values, or `set()`, and never keeps duplicates.
  • Sets are unordered, so there is no index and no slicing; you test membership instead.
  • Union `|`, intersection `&`, difference `-` and symmetric difference `^` compare two sets.
  • `set(list)` is the shortest way to remove duplicates while keeping the values.

4

set operations: union, intersection, difference, symmetric difference

Python docs

0

duplicates a set will store

Python docs

What a set is

A set is an unordered collection of unique values. Add the same value twice and the second one is simply not there. Because there is no order, there is also no index: s[0] is an error.

marks = {45, 67, 89, 67}
print(marks)          # {45, 67, 89} — the repeat is gone

The program

# sets.py — uniqueness and the four comparisons

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

print(sorted(a | b))    # [1, 2, 3, 4, 5]  union
print(sorted(a & b))    # [3, 4]           intersection
print(sorted(a - b))    # [1, 2]           difference
print(sorted(a ^ b))    # [1, 2, 5]        symmetric difference

a.add(6)
a.discard(2)
print(sorted(a))        # [1, 3, 4, 6]
print(5 in a, len(a))   # False 4

rolls = [11, 12, 11, 13, 12]
print(len(rolls), sorted(set(rolls)))   # 5 [11, 12, 13]

How it works, step by step

  1. a | b is the union: every value that appears in either set, without repeats.
  2. a & b is the intersection: only the values in both.
  3. a - b is the difference: values in a that are not in b.
  4. a ^ b is the symmetric difference: values in exactly one of the two.
  5. add() inserts one value, discard() removes one if present. remove() does the same but raises an error when the value is absent.
  6. set(rolls) throws away duplicates, and sorted() is used only so the output has a predictable order.

What it prints

[1, 2, 3, 4, 5]
[3, 4]
[1, 2]
[1, 2, 5]
[1, 3, 4, 6]
False 4
5 [11, 12, 13]

Sets compared with lists and dictionaries

CollectionOrderDuplicatesTypical use
ListkeptallowedA sequence of records
TuplekeptallowedA fixed group of values
Dictionarykeptkeys uniqueLookup by name
Setnonenot allowedUniqueness and comparisons

Common mistakes

  • {} creates an empty dictionary, not an empty set. Use set().
  • Expecting an order from a set and printing it directly. Sort it first when the order matters to a reader.
  • Putting a list inside a set. Set items must be hashable, so use a tuple.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Create a set of five numbers with one duplicate and print it, explaining what happened.
  2. Take two sets, one of students who play cricket and one of those who play football, and print both groups and only the shared names.
  3. Remove duplicates from a list of roll numbers with `set()` and print the count before and after.
  4. Check whether one set is a subset of another with `<=`.

Sources

Frequently asked questions

What is a set in Python?

An unordered collection of unique values. It removes duplicates automatically, supports fast membership tests, and provides union, intersection and difference for comparing collections.

How do I remove duplicates from a list?

Convert it: set(my_list). That gives you the unique values, though in no particular order. Wrap it in sorted() if you need them ordered.

What is the difference between a set and a list?

A list keeps order and allows duplicates, and you reach items by index. A set has no order, no duplicates, and is used for membership tests and comparisons.

What does a - b mean for two sets?

The difference: the values that are in a but not in b. The order matters, because b - a usually gives a different answer.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.