logo
Python Data Structures - Interview Questions and Answers
What are sets in Python? How are they different from lists?
What Are Sets in Python?

A set in Python is an unordered, mutable, and unique collection of elements. It is similar to a list, but it does not allow duplicate values and is optimized for fast lookups.

Syntax :
my_set = {1, 2, 3, 4, 5}  # Defining a set
empty_set = set()  # Creating an empty set (NOT {})

Important: {} creates an empty dictionary, not an empty set.


How Are Sets Different from Lists?
Feature Set (set) List (list)
Order Unordered Ordered
Duplicates No duplicates allowed Duplicates allowed
Mutability Mutable (can add/remove elements) Mutable
Indexing No indexing (cannot access elements by position) Supports indexing
Performance Faster for membership tests (in operator) Slower for membership tests
Use Case Unique elements, fast lookups, set operations Ordered collections, duplicates allowed

Examples :
1. Removing Duplicates Using a Set
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list)  # Removes duplicates
print(unique_set)  # Output: {1, 2, 3, 4, 5}

* Sets are useful for removing duplicates from lists.


2. Adding and Removing Elements in a Set
my_set = {1, 2, 3}

# Add an element
my_set.add(4)
print(my_set)  # Output: {1, 2, 3, 4}

# Remove an element
my_set.remove(2)
print(my_set)  # Output: {1, 3, 4}

# Discard (won't raise an error if the element is missing)
my_set.discard(10)  # No error

3. Set Operations (Union, Intersection, Difference)
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

# Union (A ∪ B): Combines both sets
print(A | B)  # Output: {1, 2, 3, 4, 5, 6}

# Intersection (A ∩ B): Common elements
print(A & B)  # Output: {3, 4}

# Difference (A - B): Elements in A but not in B
print(A - B)  # Output: {1, 2}

# Symmetric Difference (A ⊕ B): Elements in either A or B, but not both
print(A ^ B)  # Output: {1, 2, 5, 6}

* Sets are powerful for mathematical operations and fast lookups.


When to Use Sets Over Lists?
  • When uniqueness of elements is required (e.g., storing unique IDs).
  • When fast membership tests are needed (x in my_set is faster than x in my_list).
  • When performing set operations like union, intersection, or difference.