Sets in Python are unordered collections of unique elements. They are used when the existence of an item in a collection is more important than the order or how many times it occurs. Using sets can significantly improve performance for membership tests compared to lists or tuples, especially for large datasets. Here’s an overview of sets with various examples.
Creating a Set
You can create a set by placing all the items (elements) inside curly braces {}
, separated by commas, or by using the set()
constructor.
Example:
1 2 3 4 5 6 |
my_set = {1, 2, 3} print(my_set) # Using the set() constructor my_set = set([1, 2, 3, 2]) print(my_set) # Duplicates will be removed, output: {1, 2, 3} |
Adding Elements
You can add elements to a set using the add()
method for a single element and update()
method for multiple elements.
Example:
1 2 3 4 5 |
my_set.add(4) print(my_set) # Output: {1, 2, 3, 4} my_set.update([5, 6, 7]) print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7} |
Removing Elements
Use remove()
or discard()
to remove an item from a set. remove()
raises a KeyError if the item doesn’t exist in the set, while discard()
does not.
Example:
1 2 3 4 |
my_set.remove(4) print(my_set) # Output: {1, 2, 3, 5, 6, 7} my_set.discard(10) # Does nothing if 10 is not in the set |
Set Operations
Sets support mathematical operations like union, intersection, difference, and symmetric difference.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
a = {1, 2, 3, 4} b = {3, 4, 5, 6} # Union print(a | b) # Output: {1, 2, 3, 4, 5, 6} # Intersection print(a & b) # Output: {3, 4} # Difference print(a - b) # Output: {1, 2} # Symmetric Difference print(a ^ b) # Output: {1, 2, 5, 6} |
Checking for Membership
You can check if an item exists in a set using the in
keyword.
Example:
1 2 |
print(1 in a) # Output: True print(7 in a) # Output: False |
Set Comprehension
Set comprehensions allow you to create sets from existing iterables in a concise way, similar to list comprehensions.
Example:
1 2 |
squared_set = {x**2 for x in range(10)} print(squared_set) # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81} |
Immutable Sets (frozenset)
Python also provides an immutable version of a set called frozenset
. It can be used as a key in a dictionary or as an element of another set, which is not possible with regular sets.
Example:
1 2 |
immutable_set = frozenset([1, 2, 3]) print(immutable_set) |
Sets are a powerful feature in Python, offering efficient and easy-to-use methods for handling unique collections of items. Understanding how to work with sets can greatly enhance your data manipulation and analysis capabilities in Python.