Contents

Python Quick Guide - Step 2 Control Flow (5) - Loops(3): Comprehensions

Info
  • 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.”

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 is a concise syntax for generating lists using loops.

List Comprehension
[expression using element for element in iterable]

The above list comprehensions generate the same lists as the following for loops:

You can also add conditions to comprehensions:

List Comprehension (with condition)
[expression using element for element in iterable if condition on element]

The code to create the above lists using for loops is as follows:

List comprehensions also support nested loops:

List Comprehension (nested loops)
[expression for element in iterable for element2 in iterable2 ...]

This generates the same list as the following for loop:

Order of Nested Loops

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.

Style Guide
  • Split comprehensions across multiple lines if they become too long
  • Consider using traditional loops if comprehensions become too complex and reduce readability
📚Exercise

Calculate the result of 1 * 1 + 2 * 2 + ... + 100 * 100 using list comprehension.

Sample Answer
📚Exercise

Create a list of numbers from 1 to 20 that are multiples of 3 or 5 using list comprehension.

Sample Answer
📚Exercise

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
]
  1. Display a list of all vacant rooms
  2. 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
Column: Comparing Speed of List Comprehensions vs. Regular Loops

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 is a syntax for concisely generating dictionaries using loops.

Dictionary Comprehension
{key expression: value expression for element in iterable if condition}

You can also transform existing dictionaries using dictionary comprehension:

📚Exercise

You have a dictionary recording student scores.

  1. Create a dictionary of only the students who passed (score 60 or above)
  2. 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 is a syntax for concisely generating sets using loops.

Set Comprehension
{expression for element in iterable if condition}

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.
Generator Expression
(expression for element in iterable if condition)
📚Exercise

Calculate 1 * 1 + 2 * 2 + ... + 100 * 100 using a memory-efficient generator expression, as we did in the list comprehension Exercise.

Sample Answer
Column: Comparing Memory Efficiency of List Comprehensions and Generator Expressions

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.

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

Related Content