Sets are a fundamental data structure in Python that store collections of unique elements. Unlike lists or tuples, sets automatically eliminate any duplicate values. This makes them particularly useful when you need to ensure all items in a collection are distinct. Additionally, sets support efficient mathematical operations like union, intersection, difference, and symmetric difference.
In this tutorial, we'll explore how to create sets, understand their properties, perform various set operations, and learn about the frozenset type and set comprehensions.
Sets in Python are unordered collections of unique elements. They are defined using curly braces {} or by using the set() constructor. Sets are mutable, meaning you can add or remove items after their creation. However, since sets are unordered, they do not support indexing or slicing like lists or tuples.
Understanding sets is crucial for tasks that require uniqueness and efficient set operations, making them a valuable tool in your Python programming toolkit.
You can create a set by enclosing elements within curly braces. Each element must be separated by a comma.
1# Create a set using curly braces2fruits = {"apple", "banana", "cherry"}3print(fruits)
{'banana', 'apple', 'cherry'}set() ConstructorYou can also create a set using the set() constructor. This is particularly useful when converting other iterable types like lists or tuples into sets.
1# Create a set from a list2numbers = [1, 2, 3, 4, 5]3unique_numbers = set(numbers)4print(unique_numbers)
{1, 2, 3, 4, 5}To create an empty set, you must use the set() constructor. Using curly braces {} creates an empty dictionary, not a set.
1# Creating an empty set using set()2empty_set = set()3print(type(empty_set))45# This will create an empty dictionary, not a set6empty_dict = {}7print(type(empty_dict))
<class 'set'> <class 'dict'>
One of the most significant properties of sets is that they automatically eliminate duplicate values. When you add elements to a set, any duplicates are ignored.
1# Duplicates are automatically removed2fruits = {"apple", "banana", "cherry", "apple"}3print(fruits)
{'banana', 'apple', 'cherry'}Sets support several mathematical operations, which can be performed using methods or operators.
The union of two sets is a set containing all elements from both sets. You can use the union() method or the | operator to find the union.
1# Using union() method2set1 = {1, 2, 3}3set2 = {3, 4, 5}4union_set = set1.union(set2)5print(union_set)67# Using | operator8union_operator_set = set1 | set29print(union_operator_set)
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}The intersection of two sets is a set containing only the elements that are common to both sets. You can use the intersection() method or the & operator to find the intersection.
1# Using intersection() method2set1 = {1, 2, 3}3set2 = {3, 4, 5}4intersection_set = set1.intersection(set2)5print(intersection_set)67# Using & operator8intersection_operator_set = set1 & set29print(intersection_operator_set)
{3}
{3}The difference of two sets is a set containing elements that are in the first set but not in the second. You can use the difference() method or the - operator to find the difference.
1# Using difference() method2set1 = {1, 2, 3}3set2 = {3, 4, 5}4difference_set = set1.difference(set2)5print(difference_set)67# Using - operator8difference_operator_set = set1 - set29print(difference_operator_set)
{1, 2}
{1, 2}The symmetric difference of two sets is a set containing elements that are in either of the sets but not in their intersection. You can use the symmetric_difference() method or the ^ operator to find the symmetric difference.
1# Using symmetric_difference() method2set1 = {1, 2, 3}3set2 = {3, 4, 5}4symmetric_difference_set = set1.symmetric_difference(set2)5print(symmetric_difference_set)67# Using ^ operator8symmetric_difference_operator_set = set1 ^ set29print(symmetric_difference_operator_set)
{1, 2, 4, 5}
{1, 2, 4, 5}frozensetA frozenset is an immutable version of a set. Once created, you cannot add or remove elements from it. This makes frozensets hashable and suitable for use as dictionary keys or elements of other sets.
1# Creating a frozenset2immutable_set = frozenset([1, 2, 3])3print(immutable_set)45# Trying to modify a frozenset will raise an error6try:7immutable_set.add(4)8except AttributeError as e:9print(e)
frozenset({1, 2, 3})
'frozenset' object has no attribute 'add'Set comprehensions provide a concise way to create sets. They are similar to list comprehensions but use curly braces {}.
1# Using set comprehension to create a set of squares2squares = {x**2 for x in range(10)}3print(squares)
{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}Let's create a practical example that demonstrates the use of sets in a real-world scenario. We'll write a program to find common elements between two lists and unique elements in each list.
1# Define two lists2list1 = [1, 2, 3, 4, 5]3list2 = [4, 5, 6, 7, 8]45# Convert lists to sets6set1 = set(list1)7set2 = set(list2)89# Find common elements (intersection)10common_elements = set1.intersection(set2)11print(f"Common elements: {common_elements}")1213# Find unique elements in each list (difference)14unique_in_list1 = set1.difference(set2)15unique_in_list2 = set2.difference(set1)16print(f"Unique in list1: {unique_in_list1}")17print(f"Unique in list2: {unique_in_list2}")
Common elements: {4, 5}
Unique in list1: {1, 2, 3}
Unique in list2: {8, 6, 7}set() constructor.frozenset type provides an immutable version of sets.| Operation | Method | Operator |
|---|---|---|
| Union | union() | ` |
| Intersection | intersection() | & |
| Difference | difference() | - |
| Symmetric Difference | symmetric_difference() | ^ |
In the next tutorial, we'll explore Python Arrays, which are a more efficient way to store large arrays of numerical data compared to lists. Understanding arrays will be beneficial for tasks involving numerical computations and data analysis.
Stay tuned!