Progress0%

9 of 20 topics completed

Python Sets

Sets are unordered collections of unique elements, perfect for removing duplicates and performing mathematical set operations.

Quick Overview

Uniqueness

Automatically removes duplicates

Operations

Union, intersection, difference

Mutability

Mutable sets and immutable frozensets

Creating Sets

Learn different ways to create and initialize sets in Python.

Python
1# Creating an empty set
2empty_set = set() # Don't use {} (creates empty dict)
3
4# Creating a set with values
5numbers = {1, 2, 3, 4, 5}
6fruits = {"apple", "banana", "orange"}
7
8# Create set from list (removes duplicates)
9numbers_list = [1, 2, 2, 3, 3, 3, 4, 4, 5]
10unique_numbers = set(numbers_list)
11print(unique_numbers) # {1, 2, 3, 4, 5}
12
13# Create set from string
14chars = set("hello")
15print(chars) # {'h', 'e', 'l', 'o'}
16
17# Create immutable frozenset
18frozen = frozenset([1, 2, 3])
19# frozen.add(4) # Error: frozenset is immutable

Set Operations

Explore powerful set operations for working with multiple sets.

Python
1# Define two sets
2A = {1, 2, 3, 4, 5}
3B = {4, 5, 6, 7, 8}
4
5# Union (all unique elements from both sets)
6union = A | B # or A.union(B)
7print(union) # {1, 2, 3, 4, 5, 6, 7, 8}
8
9# Intersection (elements present in both sets)
10intersection = A & B # or A.intersection(B)
11print(intersection) # {4, 5}
12
13# Difference (elements in A but not in B)
14difference = A - B # or A.difference(B)
15print(difference) # {1, 2, 3}
16
17# Symmetric difference (elements in either A or B, but not both)
18sym_diff = A ^ B # or A.symmetric_difference(B)
19print(sym_diff) # {1, 2, 3, 6, 7, 8}
20
21# Check if one set is subset of another
22C = {1, 2}
23is_subset = C <= A # True
24is_proper_subset = C < A # True
25
26# Check if one set is superset of another
27is_superset = A >= C # True
28is_proper_superset = A > C # True

Modifying Sets

Learn how to add, remove, and modify elements in sets.

Python
1# Create a set
2numbers = {1, 2, 3}
3
4# Add single element
5numbers.add(4)
6print(numbers) # {1, 2, 3, 4}
7
8# Add multiple elements
9numbers.update([5, 6, 7])
10print(numbers) # {1, 2, 3, 4, 5, 6, 7}
11
12# Remove element (raises error if not found)
13numbers.remove(7)
14
15# Remove element (no error if not found)
16numbers.discard(8) # No error
17
18# Remove and return arbitrary element
19popped = numbers.pop()
20
21# Remove all elements
22numbers.clear()
23
24# Check membership
25if 1 in numbers:
26 print("1 is in the set")
27
28# Iterate through set
29for num in numbers:
30 print(num)

Common Use Cases

Discover practical applications of sets in Python programming.

Python
1# Remove duplicates from a list
2numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]
3unique_numbers = list(set(numbers))
4
5# Find common elements
6list1 = [1, 2, 3, 4, 5]
7list2 = [4, 5, 6, 7, 8]
8common = set(list1) & set(list2)
9
10# Find unique words in text
11text = "the quick brown fox jumps over the lazy dog"
12unique_words = set(text.split())
13
14# Track visited items
15visited = set()
16def process_item(item):
17 if item not in visited:
18 visited.add(item)
19 # Process item...
20
21# Set comprehension
22squares = {x**2 for x in range(10)}
23even_squares = {x**2 for x in range(10) if x % 2 == 0}

🎯 Practice Exercise

Create a program to analyze text using sets:

Python
1# 1. Create a function that:
2# - Takes two texts as input
3# - Returns:
4# * Unique words in each text
5# * Common words between texts
6# * Words exclusive to each text
7
8# 2. Create a function to:
9# - Find character types in text
10# - Count unique:
11# * Letters
12# * Numbers
13# * Special characters
14
15# 3. Implement a simple spell checker:
16# - Use a set of known words
17# - Find misspelled words
18# - Suggest corrections

Related Tutorials

Work with key-value pair data structures.

Learn more

Master sequence types in Python.

Learn more

Compare different Python data structures.

Learn more