Welcome to The Coding College, your go-to resource for mastering programming concepts! In this guide, we’ll explore Python sets, a unique data structure designed for storing unordered and unindexed collections of items.
By the end of this tutorial, you’ll understand how sets work, their advantages, and how to use them effectively in Python.
What Are Sets in Python?
A set is a collection type in Python that:
- Is unordered: The items have no defined order.
- Is unindexed: Items cannot be accessed by position.
- Contains unique elements: Duplicates are automatically removed.
Sets are useful for tasks like removing duplicates, performing mathematical operations (union, intersection), and efficient membership testing.
How to Create a Set
Sets are defined using curly braces {}
or the set()
constructor.
Example 1: Creating a Set
# Using curly braces
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
# Using the set() constructor
another_set = set([1, 2, 2, 3])
print(another_set) # Output: {1, 2, 3}
Key Features of Sets
- Unordered:
The order of elements in a set may vary, and it cannot be relied upon.
example_set = {3, 1, 4, 2}
print(example_set) # Output: {1, 2, 3, 4} (order may vary)
- Unique Elements:
Duplicate elements are automatically removed.
duplicates = {1, 1, 2, 3, 3}
print(duplicates) # Output: {1, 2, 3}
- Immutable Elements:
Sets can only contain immutable (unchangeable) items like numbers, strings, or tuples.
valid_set = {1, "hello", (2, 3)}
# invalid_set = {1, [2, 3]} # Raises a TypeError
Accessing Set Items
Since sets are unordered and unindexed, you cannot access elements using an index. However, you can:
1. Iterate Through a Set
Use a for
loop to access each item.
my_set = {10, 20, 30}
for item in my_set:
print(item)
2. Check Membership
Use the in
keyword to check if an item exists in the set.
my_set = {"apple", "banana", "cherry"}
print("apple" in my_set) # Output: True
Set Methods and Operations
Adding and Removing Items
add()
: Add a single item to the set.update()
: Add multiple items (from another set, list, etc.).remove()
: Remove an item; raises an error if it doesn’t exist.discard()
: Remove an item; doesn’t raise an error if it doesn’t exist.pop()
: Remove a random item.
Example:
fruits = {"apple", "banana"}
# Add items
fruits.add("cherry")
print(fruits) # Output: {'apple', 'banana', 'cherry'}
# Update items
fruits.update(["mango", "orange"])
print(fruits) # Output: {'apple', 'banana', 'cherry', 'mango', 'orange'}
# Remove items
fruits.remove("banana")
print(fruits) # Output: {'apple', 'cherry', 'mango', 'orange'}
# Discard items (safe removal)
fruits.discard("grape") # No error raised
Mathematical Set Operations
Python sets support mathematical operations like union, intersection, difference, and symmetric difference.
Operation | Method | Description | Example |
---|---|---|---|
Union | union() | Combines all unique elements from both sets. | `{1, 2} |
Intersection | intersection() | Retains only elements common to both sets. | {1, 2} & {2, 3} => {2} |
Difference | difference() | Returns elements unique to the first set. | {1, 2} - {2, 3} => {1} |
Symmetric Difference | symmetric_difference() | Elements unique to either set, not both. | {1, 2} ^ {2, 3} => {1, 3} |
Example:
A = {1, 2, 3}
B = {3, 4, 5}
# Union
print(A | B) # Output: {1, 2, 3, 4, 5}
# Intersection
print(A & B) # Output: {3}
# Difference
print(A - B) # Output: {1, 2}
# Symmetric Difference
print(A ^ B) # Output: {1, 2, 4, 5}
Built-In Functions for Sets
Python provides several built-in functions to work with sets.
Function | Description | Example |
---|---|---|
len() | Returns the number of elements in the set. | len({1, 2, 3}) => 3 |
min() | Returns the smallest element. | min({10, 20, 30}) => 10 |
max() | Returns the largest element. | max({10, 20, 30}) => 30 |
sum() | Returns the sum of all elements. | sum({1, 2, 3}) => 6 |
sorted() | Returns a sorted list from the set. | sorted({3, 1, 2}) => [1, 2, 3] |
Use Cases of Sets
- Removing Duplicates
Convert a list with duplicates into a set to keep only unique elements.
my_list = [1, 2, 2, 3, 4, 4]
unique = set(my_list)
print(unique) # Output: {1, 2, 3, 4}
- Efficient Membership Testing
Sets provide faster membership checks compared to lists.
my_set = {1, 2, 3}
print(2 in my_set) # Output: True
- Mathematical Operations
Solve problems like finding common or unique items between groups.
Practice Exercises
- Create a set from the list
[10, 20, 30, 40, 10, 20]
and print it. - Add the element
"orange"
to the set{"apple", "banana"}
. - Find the intersection of
{1, 2, 3}
and{2, 3, 4}
. - Use the
discard()
method to safely remove"blue"
from{"red", "blue", "green"}
. - Convert the set
{3, 1, 4, 2}
into a sorted list.
Why Learn Sets with The Coding College?
At The Coding College, we simplify programming concepts and provide hands-on examples to enhance your skills. Python sets are a powerful tool for data analysis and problem-solving. Whether you’re a beginner or an experienced coder, mastering sets will elevate your programming game.
Conclusion
Python sets are versatile and efficient, making them a valuable tool for developers. By practicing the examples and exercises in this guide, you’ll gain a solid understanding of sets and their practical applications.