- What is a set — definition and characteristics
- Creating sets — syntax and different ways
- Uniqueness — sets store only unique elements
- Set vs List — key differences and when to use each
- Use cases — practical applications of sets
Introduction to Sets
A set is an unordered, mutable collection of unique elements in Python. Sets are defined using curly braces {} and can contain elements of any immutable data type.
The key characteristics of sets are:
- Unordered — elements have no defined order
- Unique — duplicate elements are automatically removed
- Mutable — elements can be added or removed
- Unindexed — elements cannot be accessed by index
- Hashable elements — only immutable types can be stored
💡 Key concept: Sets are ideal for storing unique values and performing mathematical set operations like union, intersection, and difference.
Creating Sets
Set Creation Methods
Sets can be created using curly braces {} or the set() constructor.
# Using curly braces (most common)
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'apple', 'banana', 'cherry'}
# Using the set() constructor
numbers = set([1, 2, 3, 4, 5])
print(numbers) # {1, 2, 3, 4, 5}
# Empty set (must use set() - {} creates an empty dictionary)
empty_set = set()
empty_dict = {}
print(type(empty_set)) # <class 'set'>
print(type(empty_dict)) # <class 'dict'>
# From a string (creates a set of characters)
chars = set("hello")
print(chars) # {'e', 'h', 'l', 'o'}
# From a range
numbers = set(range(5))
print(numbers) # {0, 1, 2, 3, 4}
# Mixed data types
mixed = {1, "hello", 3.14, True}
print(mixed) # {1, 3.14, 'hello'}
Important notes:
- Use
{}for non-empty sets with values - Use
set()for empty sets - Sets automatically remove duplicates
- Elements must be immutable (hashable)
Quick Check: What is the correct way to create an empty set? (Answer: set() — {} creates an empty dictionary)
Key Characteristics
Understanding Set Properties
Sets have several unique properties that distinguish them from other data structures.
# 1. Uniqueness (no duplicates)
numbers = {1, 2, 2, 3, 3, 3, 4}
print(numbers) # {1, 2, 3, 4} — duplicates removed
# 2. Unordered (order is not guaranteed)
fruits = {"apple", "banana", "cherry"}
print(fruits) # Order may vary: {'cherry', 'apple', 'banana'}
# 3. Mutable (can be modified)
fruits = {"apple", "banana", "cherry"}
fruits.add("mango")
print(fruits) # {'apple', 'banana', 'cherry', 'mango'}
fruits.remove("banana")
print(fruits) # {'apple', 'cherry', 'mango'}
# 4. Unindexed (cannot access by index)
fruits = {"apple", "banana", "cherry"}
# print(fruits[0]) # TypeError: 'set' object is not subscriptable
# 5. Elements must be hashable (immutable)
valid_set = {1, "hello", (1, 2)} # Valid
# invalid_set = {1, [1, 2]} # TypeError: unhashable type: 'list'
Key properties:
- Uniqueness — automatically removes duplicates
- Unordered — cannot rely on element order
- Mutable — can add and remove elements
- Hashable elements — only immutable types allowed
- No indexing — cannot access by position
Quick Check: Can a set contain a list as an element? (Answer: No — lists are mutable and unhashable)
Set vs List
Key Differences
Understanding the differences between sets and lists helps you choose the right data structure for your needs.
# Comparison of set and list
# 1. Uniqueness
my_list = [1, 2, 2, 3, 3, 3, 4]
my_set = {1, 2, 2, 3, 3, 3, 4}
print(my_list) # [1, 2, 2, 3, 3, 3, 4] — duplicates allowed
print(my_set) # {1, 2, 3, 4} — duplicates removed
# 2. Ordering
my_list = [1, 2, 3]
my_set = {1, 2, 3}
print(my_list[0]) # 1 — index access works
# print(my_set[0]) # TypeError — no index access
# 3. Performance (membership testing)
import time
large_list = list(range(1000000))
large_set = set(range(1000000))
start = time.time()
999999 in large_list
print(f"List membership: {time.time() - start:.6f}s")
start = time.time()
999999 in large_set
print(f"Set membership: {time.time() - start:.6f}s")
# 4. Mutability
my_list = [1, 2, 3]
my_set = {1, 2, 3}
my_list[0] = 10 # Works
# my_set[0] = 10 # TypeError
When to use each:
- Use sets when:
- You need to store unique values
- Fast membership testing is important
- Order doesn't matter
- You need mathematical set operations
- Use lists when:
- Order matters
- You need index access
- Duplicates are allowed
- You need to modify elements by position
Practical Use Cases
Real-World Applications
Sets are used in many practical scenarios in Python programming.
# 1. Removing duplicates from a list
original = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique = list(set(original))
print(unique) # [1, 2, 3, 4, 5] (order may vary)
# 2. Finding common elements (intersection)
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
common = set1 & set2
print(common) # {4, 5}
# 3. Finding differences
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
difference = set1 - set2
print(difference) # {1, 2, 3}
# 4. Finding unique elements (symmetric difference)
unique_items = set1 ^ set2
print(unique_items) # {1, 2, 3, 6, 7, 8}
# 5. Checking for duplicates in a collection
items = [1, 2, 3, 4, 5, 1, 2]
has_duplicates = len(items) != len(set(items))
print(has_duplicates) # True
# 6. Membership testing
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # True
print("grape" in fruits) # False
# 7. Counting unique words
text = "the cat in the hat with the cat and the hat"
words = text.split()
unique_words = set(words)
print(f"Total words: {len(words)}")
print(f"Unique words: {len(unique_words)}")
Common Mistakes
Pitfalls and Solutions
Mistake 1: Using {} to Create an Empty Set
# WRONG — creates a dictionary
empty = {}
print(type(empty)) # <class 'dict'>
# CORRECT — use set()
empty = set()
print(type(empty)) # <class 'set'>
Mistake 2: Adding Unhashable Types
# WRONG — raises TypeError
my_set = {1, 2, 3}
# my_set.add([4, 5]) # TypeError: unhashable type: 'list'
# CORRECT — use immutable types
my_set.add((4, 5)) # Tuple is hashable
Mistake 3: Assuming Set Order
# WRONG — sets are unordered
my_set = {1, 2, 3, 4, 5}
# print(my_set[0]) # TypeError
# CORRECT — use lists if order matters
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 1
Quick Check: What is the most common mistake with sets? (Answer: Using {} to create an empty set — it creates a dictionary)
Interactive Editor
Experiment with sets in the interactive editor below. Modify the code and observe the results in real time.
SET PRACTICE
========================================
1. CREATING SETS
Fruits: {'apple', 'banana', 'cherry'}
Numbers: {1, 2, 3, 4, 5}
Empty set: set()
Type of empty_set: <class 'set'>
2. UNIQUENESS
Set with duplicates: {1, 2, 3, 4}
3. ADDING AND REMOVING
After adding mango: {'apple', 'banana', 'cherry', 'mango'}
After removing banana: {'apple', 'cherry', 'mango'}
4. SET OPERATIONS
Set1: {1, 2, 3, 4, 5}
Set2: {4, 5, 6, 7, 8}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (set1 - set2): {1, 2, 3}
5. REMOVING DUPLICATES
Original: [1, 2, 2, 3, 3, 3, 4, 5, 5]
Unique: [1, 2, 3, 4, 5]
Set practice complete!
Certificate of Completion
You have completed the Python Set tutorial. You now understand set creation, uniqueness, characteristics, and the key differences between sets and lists.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about sets:
Frequently Asked Questions
What is a set in Python?
{} and automatically remove duplicates.
What is the difference between a set and a list?
How do I create an empty set?
set() to create an empty set. Using {} creates an empty dictionary, not a set.
Can a set contain mutable elements?
Are sets ordered in Python?
How do I remove duplicates from a list?
unique_list = list(set(my_list)). Note that this will change the order of elements.
Where to Go From Here
After mastering sets, consider exploring these related topics:
Access Set Elements
Learn how to access and iterate through set elements.
Learn More →Set Methods
Explore built-in set methods and operations.
Learn More →List vs Set
Detailed comparison of lists and sets.
Learn More →