Python Quick Guide - Step 2 Control Flow (5) - Loops(3): Comprehensions
- This course is designed to help you learn the basics of Python programming as quickly as possible through hands-on practice.
- The “Style Guide” sections primarily cover guidelines from PEP8 for writing clean Python code.
- You can run and see the results of each code example.
Feel free to experiment with the code - reloading the page will reset the content.
This is a continuation of “Step 2 Control Flow.”
2.2. Loops
2.2.3. Comprehensions
Comprehensions are syntax constructs that allow you to easily create iterable objects.
- They express traditional loop processing in a single line, making code more concise
- They generally execute faster than using
for
loops
List Comprehension
List comprehension is a concise syntax for generating lists using loops.
The above list comprehensions generate the same lists as the following for
loops:
You can also add conditions to comprehensions:
The code to create the above lists using for
loops is as follows:
List comprehensions also support nested loops:
This generates the same list as the following for
loop:
For nested loops, the for
clauses must be written in the same order as normal nested for
loops.
The above comprehension is equivalent to the following for
loop:
As shown, you must write the outer loop (for student in students_scores
) first, followed by the inner loop (for score in student
). If you reverse the order and write for score in student for student in students_scores
, it will result in an error because student
would be undefined.
- Split comprehensions across multiple lines if they become too long
- Consider using traditional loops if comprehensions become too complex and reduce readability
Calculate the result of 1 * 1 + 2 * 2 + ... + 100 * 100
using list comprehension.
Sample Answer
Create a list of numbers from 1 to 20 that are multiples of 3 or 5 using list comprehension.
Sample Answer
A hotel has the following list of vacant rooms by floor:
vacant_rooms_by_floor = [
[101, 102, 103], # vacant rooms on 1st floor
[202, 203], # vacant rooms on 2nd floor
[301, 303, 305] # vacant rooms on 3rd floor
]
- Display a list of all vacant rooms
- Rooms ending with 1 or 5 are corner rooms. Display a list of vacant corner rooms only
(Hint: You can calculate the last digit with<room number> % 10
)
Sample Answer
Let’s compare the processing speed of list comprehensions and regular loops using a benchmark tool:
From the benchmark results, we can see that the comprehension is slightly faster than the loop.
(Occasionally, the loop might be measured as faster depending on timing.)
Dictionary Comprehension
Dictionary comprehension is a syntax for concisely generating dictionaries using loops.
You can also transform existing dictionaries using dictionary comprehension:
You have a dictionary recording student scores.
- Create a dictionary of only the students who passed (score 60 or above)
- Create a dictionary mapping each passing student to an evaluation: “Excellent” for 80 or above, “Good” for others (Hint: Use the ternary operator)
Sample Answer
Set Comprehension
Set comprehension is a syntax for concisely generating sets using loops.
Generator Expressions
Generator expressions are similar to comprehensions but return a generator object that yields values one at a time as needed, rather than generating all values at once.
- They are memory-efficient, making them useful when dealing with large datasets.
- Note that once used, they become empty and cannot be reused.
Calculate 1 * 1 + 2 * 2 + ... + 100 * 100
using a memory-efficient generator expression, as we did in the list comprehension Exercise.
Sample Answer
Let’s compare the memory efficiency of list comprehensions and generator expressions using a benchmark tool.
From the benchmark results above, we can see that generator expressions use less memory regardless of size, while list comprehensions use more memory proportional to the size.
Comprehension Summary
Type | Syntax | Use | Key Features |
---|---|---|---|
List Comprehension | [<expression> for <element> in <iterable> if <condition>] |
Creating lists | Concisely generate lists |
Dictionary Comprehension | {<key>: <value> for <element> in <iterable> if <condition>} |
Creating dictionaries | Concisely generate dictionaries |
Set Comprehension | {<expression> for <element> in <iterable> if <condition>} |
Creating sets | Concisely generate sets |
Generator Expression | (<expression> for <element> in <iterable> if <condition>) |
Lazy evaluation | Memory efficient, one-time use |
- List comprehensions generally execute faster than regular loops
- Consider using traditional loops if comprehensions become too complex and reduce readability
- Use generator expressions when dealing with large datasets to reduce memory usage