Back to Python
2026-01-015 min read

Sets (Python Programming)

Learn Sets (Python Programming) step by step with clear examples and exercises.

Title: Python Sets - Mastering Data Structures for Efficient Programming

Why This Matters

In this lesson, we will delve into Python's Set data structure, a powerful tool that enables efficient and unique storage of collections of elements. Understanding how to use sets can significantly improve the performance of your code, especially when dealing with large datasets. Additionally, mastering sets is crucial for acing programming interviews, as they often include questions related to this versatile data structure.

Python sets offer several advantages over other data structures such as lists:

  • Efficient storage: Since sets only store unique elements, they consume less memory compared to lists that may contain duplicate values.
  • Fast operations: Set operations like intersection, union, difference, and symmetric difference have constant time complexity (O(1)) for small sets, making them ideal for large datasets.
  • Mathematical notation: Python sets can be used with mathematical notation for set operations, which makes the code more readable and easier to understand.

Prerequisites

Before diving into Python Sets, you should have a solid understanding of the following concepts:

  • Basic Python syntax and control structures (if/else, loops)
  • Variables and data types (integers, strings, lists)
  • Familiarity with mathematical set operations (union, intersection, difference, symmetric difference)

Core Concept

A Set is an unordered collection of unique elements. In Python, sets are implemented as a built-in data type, and they provide several advantages over other data structures such as lists:

  1. Efficient storage: Since sets only store unique elements, they consume less memory compared to lists that may contain duplicate values.
  2. Fast operations: Set operations like intersection, union, difference, and symmetric difference have constant time complexity (O(1)) for small sets, making them ideal for large datasets.
  3. Mathematical notation: Python sets can be used with mathematical notation for set operations, which makes the code more readable and easier to understand.

Creating a Set in Python

Creating an empty set

my_set = set()

Creating a set using list comprehension

numbers = {num for num in range(10)}

Creating a set with specific elements

letters = {'a', 'b', 'c'}


### Set Operations

Python provides several built-in functions to perform various operations on sets, such as union (`|`), intersection (`&`), difference (`-`), and symmetric difference (`^`). You can also check if a set is a subset of another set using the `<=` operator.

Worked Example

my_set1 = {'a', 'b', 'c'}

my_set2 = {'b', 'c', 'd'}

union = my_set1 | my_set2 # {'a', 'b', 'c', 'd'}

intersection = my_set1 & my_set2 # {'b', 'c'}

difference = my_set1 - my_set2 # {'a'}

symmetric_difference = my_set1 ^ my_set2 # {'a', 'd'}

subset = my_set1 <= my_set2 # False

Worked Example

Let's consider two sets representing the students enrolled in two different courses: math and science. We want to find out how many students are common between these two courses.

Students enrolled in math course

math_students = {'Alice', 'Bob', 'Charlie', 'David', 'Eve'}

Students enrolled in science course

science_students = {'Alice', 'Bob', 'Carol', 'Dave', 'Eve', 'Frank'}

Find common students between math and science courses

common_students = math_students.intersection(science_students)

print("Common students:", common_students)

Output: `Common students: {'Alice', 'Bob', 'Eve'}`

Common Mistakes

  1. Assuming set operations are like list operations: Remember that sets do not maintain the order of elements and only store unique values.
  2. Creating a set with duplicate elements: Since sets only store unique elements, attempting to create a set with duplicates will result in the removal of one instance of each duplicate.
  3. Using set methods on non-set objects: Ensure that the operands for set operations are indeed sets or can be converted to sets (e.g., using set() function).
  4. Not understanding the difference between set and list: Although both store collections, sets only store unique elements, while lists maintain the order and allow duplicate values.
  5. Forgetting that set operations are not commutative: The order of operands matters for some set operations (e.g., my_set1 & my_set2 is different from my_set2 & my_set1).

Practice Questions

  1. Write a Python program to determine if a given set is a subset of another set.
  2. Given two lists, write a Python program to convert them into sets and find the union, intersection, and difference between the sets.
  3. Write a Python program to find all possible combinations of three elements from the set {1, 2, 3, 4, 5}.
  4. What is the time complexity of finding the union, intersection, difference, and symmetric difference of two sets in Python?
  5. How can you convert a list into a set in Python?
  6. Explain the difference between a list and a set in terms of their behavior and use cases.

FAQ

  1. Why are sets faster than lists for certain operations?

Sets have constant time complexity (O(1)) for several operations like union, intersection, difference, and symmetric difference due to their hash-based implementation. Lists, on the other hand, have linear time complexity for these operations since they need to iterate through all elements.

  1. Can I convert a list to a set in Python?

Yes, you can convert a list to a set using the set() function: my_list = [1, 2, 3, 4]; my_set = set(my_list).

  1. How do I check if an element is in a set?

To check if an element is in a set, you can use the in keyword: element in my_set. If the element exists in the set, it returns True, otherwise False.

  1. What are some common set operations and their mathematical notation equivalents?
  • Union (|): U(A, B)
  • Intersection (&): A ∩ B
  • Difference (-): A - B
  • Symmetric difference (^): A Δ B
  1. What is the difference between a list and a set in terms of their behavior and use cases?

Lists maintain the order of elements and allow duplicate values, while sets only store unique elements without any particular order. Lists are more suitable for sequential data or when preserving the order matters, whereas sets are ideal for efficient storage and fast set operations on large datasets.

Sets (Python Programming) | Python | XQA Learn