Introduction
In this lesson, we will explore Python sets, a collection type designed for storing unique elements. Sets provide efficient operations for combining and comparing data, making them essential for many practical programming tasks. We will cover how sets differ from other collection types, create sets using various methods, perform core set operations like union and intersection, and introduce frozenset for immutable collections.
What are Sets?
Sets are an unordered collection of unique elements in Python. Unlike lists or tuples, which allow duplicates and ordering, sets automatically eliminate duplicate values, and their elements are not indexed. This distinction allows sets to be optimized for membership testing, removing duplicates, and performing mathematical set operations.
Creating Sets
You can create a set using curly braces {} or the set() constructor. Let’s see both approaches:
Using Set Literals
# Creating a set with literals
fruits = {"apple", "banana", "cherry", "apple"} # Duplicate "apple" is ignored
print(fruits)
# Output
{'cherry', 'banana', 'apple'}
Using the set() Constructor
# Creating a set from a list
numbers_list = [1, 2, 3, 4, 4, 2]
numbers_set = set(numbers_list)
print(numbers_set)
# Output
{1, 2, 3, 4}
Set Operations
Sets support several key operations that are useful for comparing collections:
Union
The union operation combines all elements from both sets, removing duplicates:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set)
# Output
{1, 2, 3, 4, 5}
Intersection
Returns only the elements present in both sets:
intersection_set = set_a.intersection(set_b)
print(intersection_set)
# Output
{3}
Difference
This operation finds elements in one set and not the other:
difference_set = set_a.difference(set_b)
print(difference_set)
# Output
{1, 2}
Symmetric Difference
Returns elements present in either of the sets but not their intersection:
symmetric_difference_set = set_a.symmetric_difference(set_b)
print(symmetric_difference_set)
# Output
{1, 2, 4, 5}
Membership Tests and Set Methods
Sets excel at membership testing, efficiently checking for the presence of an element:
if 3 in set_a:
print("3 is in set_a")
Sets also offer built-in methods to handle duplicates and filter data intuitively:
add(element): Adds an element to the set.remove(element): Removes an element; raises an error if not present.discard(element): Removes an element; does not raise an error.
Frozenset
A frozenset is an immutable version of a set. Once created, its elements cannot be changed, making it useful for dictionary keys or caching:
fs = frozenset([1, 2, 3, 2])
print(fs)
# Output
frozenset({1, 2, 3})
Summary / Key Takeaways
In this lesson on Sets and Set Operations, you have learned:
- Sets are unordered collections of unique elements, ideal for removing duplicates and membership testing.
- Creating sets can be done using literals or the
set()constructor from iterables. - Core operations, such as union, intersection, difference, and symmetric difference, allow combining or comparing sets efficiently.
- Membership tests and methods like
add(),remove(), anddiscard()help manage set elements effectively. - Frozensets provide immutable sets suitable for use in scenarios requiring constant collections, such as dictionary keys.
