Chapter 9: A Shortcut to Loops - The Magic of Comprehensions
So far, whenever you've needed to create a new list from an existing one, you've probably reached for a for loop. It's reliable, clear, and gets the job done.
For example, let's say we have a list of numbers and we want to create a new list containing the square of each number. The classic for loop approach looks like this:
numbers = [1, 2, 3, 4, 5]
squares = [] # 1. Create an empty list
for number in numbers: # 2. Loop through the original list
squares.append(number * number) # 3. Append the new value
print(squares)
# Output: [1, 4, 9, 16, 25]This works perfectly, but it takes three lines to express a single idea: "create a new list of squares from the numbers list." In Python, there's often a more direct, elegant, and efficient way to handle common tasks like this. For this job, we can use a comprehension.
A comprehension is a compact way to create a new sequence (like a list, set, or dictionary) based on an existing one. It's like a shorthand for a for loop that lets you write more expressive and readable code.
List Comprehensions: Your New Best Friend
The most common type is the list comprehension. It takes the three steps from our example above and combines them into a single, readable line.
The basic syntax is: new_list = [expression for item in iterable]
Let's break that down:
[ ]: The square brackets tell Python you're creating a new list.expression: This is what you want to do to each item. In our example, it'snumber * number.for item in iterable: This is the loop part, exactly like in a standardforloop.
Let's rewrite our squaring example using a list comprehension:
See how that one line says exactly what it's doing? "Make a list of number * number for each number in numbers." It's clean, concise, and widely used by Python developers—a truly "Pythonic" way of writing code.
Adding a Filter with if
ifWhat if you only want to include certain items in your new list? Comprehensions have a built-in way to filter elements using an if clause.
The syntax is: new_list = [expression for item in iterable if condition]
Let's find the squares of only the odd numbers from our list.
First, the old for loop way:
Now, the comprehension way:
The if statement is placed at the end, and it filters the items from the iterable before the expression is even applied to them. It's a powerful way to transform and filter data in a single step.
Beyond Lists: Dictionary and Set Comprehensions
This powerful idea isn't limited to just lists. You can use a similar syntax to build dictionaries and sets on the fly.
Dictionary Comprehensions
Dictionaries need a key and a value. The comprehension syntax is slightly different to accommodate this, using curly braces {} and a colon :.
The syntax is: new_dict = {key_expression: value_expression for item in iterable}
Let's create a dictionary where the keys are numbers and the values are their squares.
Set Comprehensions
Set comprehensions look almost identical to list comprehensions but use curly braces {}. Remember that sets only store unique values, which makes this comprehension perfect for de-duplicating items.
The syntax is: new_set = {expression for item in iterable}
Imagine you have a list of words with duplicates and different casings, and you want a set of all the unique words in lowercase.
Why Should You Use Comprehensions? 🤔
You might be thinking, "My for loops work just fine, why switch?" Here are a few great reasons:
They are Concise and Readable: For simple transformations and filtering, comprehensions are often easier to read at a glance than a multi-line
forloop. They describe the what instead of the how.They are Faster: In most cases, comprehensions are executed more quickly than the equivalent
forloop that uses.append()to build a list. Python is able to make optimizations behind the scenes because it knows you're building a list from the start.They are Pythonic: Using comprehensions is a hallmark of a fluent Python programmer. When you see them in other people's code (and you will!), you'll know exactly what's happening.
While they are powerful, don't overdo it! If your logic becomes very complex with multiple if conditions or nested loops, a traditional for loop might be more readable, and that's perfectly okay. Readability always counts!
Chapter Summary
Comprehensions are a concise syntax for creating lists, dictionaries, or sets from existing iterables.
List Comprehension:
[expression for item in iterable if condition]Dictionary Comprehension:
{key: value for item in iterable if condition}Set Comprehension:
{expression for item in iterable if condition}They often result in cleaner, more readable, and more efficient code than the equivalent
forloop.
Now, let's test your new skills!
✏️ Exercises
Given the list
words = ['apple', 'banana', 'cherry', 'date'], use a list comprehension to create a new list containing the length of each word. The result should be[5, 6, 6, 4].Use a list comprehension to create a list of all the numbers from 1 to 100 that are divisible by 7.
Given the list of names
names = ['Bruce', 'Clark', 'Peter'], use a dictionary comprehension to create a dictionary where the keys are the names and the values are the lengths of the names.From the string
"the quick brown fox jumps over the lazy dog", use a set comprehension to create a set of all the unique vowels (a,e,i,o,u) present in the string.
Last updated