Reading history

Python Sets: Union, Intersection and Set Methods

4 min read 2 views

Learn Python sets: creating sets, add() and discard(), removing duplicates, union, intersection, difference, subsets and set comprehensions.

A set is an unordered collection with no duplicates. Sets answer membership questions (“is this item in here?”) very quickly and support the same operations you learned in school maths: union, intersection and difference. This lesson shows how to create sets, add and remove items, remove duplicates from a list, and compare two groups.

In this lesson you will learn

  • How to create a set, including an empty one
  • How to add and remove items safely
  • How to remove duplicates from a list
  • Union, intersection, difference and symmetric difference
  • Subset checks and set comprehensions

Creating Sets and Changing Them

tags = {"python", "c", "python", "sql"}
print(sorted(tags))          # duplicates are removed
print(len(tags))

tags.add("java")
tags.discard("c")            # no error if missing
print(sorted(tags))
print("sql" in tags)

empty = set()                # {} would be an empty dict
print(type(empty).__name__, type({}).__name__)

emails = ["a@x.com", "b@x.com", "a@x.com"]
print(len(set(emails)), "unique emails")

Output

['c', 'python', 'sql']
3
['java', 'python', 'sql']
True
set dict
2 unique emails
  • The duplicate "python" was dropped automatically.
  • Sets have no order, so the examples wrap them in sorted() to print a predictable list.
  • add() inserts one item. discard() removes an item and does nothing if it is missing; remove() raises a KeyError instead.
  • set() makes an empty set. {} makes an empty dictionary.
  • len(set(items)) counts the unique values in a list.

Set Operations

python_club = {"Rafi", "Nila", "Tanim", "Sumi"}
chess_club = {"Nila", "Sumi", "Jamil"}

print("Both:", sorted(python_club & chess_club))
print("Either:", sorted(python_club | chess_club))
print("Only Python:", sorted(python_club - chess_club))
print("Exactly one:", sorted(python_club ^ chess_club))

print({"Nila"} <= chess_club)           # subset check
evens = {n for n in range(10) if n % 2 == 0}
print(sorted(evens))

Output

Both: ['Nila', 'Sumi']
Either: ['Jamil', 'Nila', 'Rafi', 'Sumi', 'Tanim']
Only Python: ['Rafi', 'Tanim']
Exactly one: ['Jamil', 'Rafi', 'Tanim']
True
[0, 2, 4, 6, 8]
OperatorMethodResult
a | ba.union(b)Items in either set
a & ba.intersection(b)Items in both sets
a - ba.difference(b)Items in a but not in b
a ^ ba.symmetric_difference(b)Items in exactly one of the sets
a <= ba.issubset(b)True if every item of a is in b

The last line of the example is a set comprehension. It looks like a list comprehension but uses curly braces.

Why Membership Tests Are Fast

Like dictionary keys, set items are stored by their hash, so x in my_set takes about the same time whether the set holds ten items or ten million. x in my_list has to check items one by one. If you test membership often, convert the list to a set first.

Common Mistakes

  1. Writing {} for an empty set. Use set().
  2. Indexing a set. s[0] fails because sets have no positions; convert to a list or sorted list first.
  3. Adding a list to a set. Items must be hashable; use a tuple.
  4. Expecting set(list) to keep the order. Use list(dict.fromkeys(items)) to remove duplicates and keep order.

Practice Exercises

Exercise 1. Find the letters that appear in both “python” and “typhoon”.

Show answer
print(sorted(set("python") & set("typhoon")))
# ['h', 'n', 'o', 'p', 't', 'y']

Exercise 2. Check whether every required skill is in a candidate’s skill set.

Show answer
required = {"python", "sql"}
candidate = {"python", "sql", "git"}
print(required <= candidate)   # True

Frequently Asked Questions

What is a frozenset?

An immutable set created with frozenset(...). Because it cannot change, it can be a dictionary key or an item of another set.

Can a set contain different types?

Yes, as long as every item is hashable, for example {1, "a", (2, 3)}.

Summary

  • Sets store unique, hashable items with no order.
  • Use add() and discard() to change them; set() creates an empty set.
  • |, &, - and ^ combine sets.
  • Membership tests on sets are much faster than on lists.

Next: handle errors with Python Exception Handling.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *