Why this topic matters: Set comprehensions are a concise and efficient way to create sets in Python. They help reduce the amount of code required to perform operations on sets, making your code cleaner, more readable, and faster.
What you'll learn: In this lesson, we will explore set comprehensions, learn how to use them effectively, and discuss common issues that may arise when working with them.
A set comprehension is a compact syntax for creating sets from iterables (e.g., lists, tuples, or other sets). It consists of square brackets []
enclosing an expression followed by a for
loop and a conditional statement (optional) separated by the word if
.
Here's a basic example:
numbers = [1, 2, 3, 4, 5]
even_numbers = {n for n in numbers if n % 2 == 0}
print(even_numbers) # Output: {2, 4}
In this example, we create a set even_numbers
containing all even numbers from the list numbers
.
Let's dive into some practical examples to illustrate the power of set comprehensions.
Assuming we have a list of duplicate usernames, we can create a set containing only unique usernames like this:
user_names = ["John", "Jane", "Sally", "John", "Sally", "Mark"]
unique_user_names = {username for username in user_names}
print(unique_user_names) # Output: {"John", "Jane", "Sally", "Mark"}
We can use set comprehensions to filter out unwanted elements from a list of tuples. For instance, consider a list of (name, age) tuples, and we want to find people older than 30:
people = [("John", 25), ("Jane", 32), ("Sally", 45), ("Mark", 18)]
adults = {person[0] for person in people if person[1] > 30}
print(adults) # Output: {"Jane", "Sally"}
What causes it: This error occurs when you try to use an undefined variable in your set comprehension.
# Bad code example that triggers the error
numbers = [1, 2, 3]
even_numbers = {n for n in num ** 2 if n % 2 == 0}
Error message:
Traceback (most recent call last):
File "example.py", line 3, in <module>
even_numbers = {n for n in num ** 2 if n % 2 == 0}
NameError: name 'num' is not defined
Solution: Make sure to define all variables before using them in your set comprehension.
Why it happens: The error occurs because num
has not been defined when the code attempts to execute the set comprehension.
How to prevent it: Always declare and initialize your variables before using them in any operation.
What causes it: This error arises when you try to iterate over an object that is not iterable or when you apply an inappropriate function to an element during set comprehension.
# Bad code example that triggers the error
numbers = [1, 2, "3"]
even_numbers = {n for n in numbers if n ** 2 == 4}
Error message:
Traceback (most recent call last):
File "example.py", line 3, in <module>
even_numbers = {n for n in numbers if n ** 2 == 4}
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'
Solution: Ensure that all elements in the iterable are of the same data type, or use appropriate conversion functions (e.g., int()
, float()
) to convert strings to numbers before performing arithmetic operations.
Why it happens: The error occurs because we're trying to raise a string to the power of 2, which is not supported in Python.
How to prevent it: Convert strings containing numbers to integers or floats before performing arithmetic operations.