Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A compact way to build lists

Open In Colab

List comprehension does not introduce new logic to Python. It simply repackages patterns you already understand into a shorter, and often clearer, form.


1. Why list comprehension exists

From boilerplate to patterns

So far, whenever you needed to create a new list based on an old list, you used the standard “append pattern”:

  1. Create an empty list

  2. Start a for loop

  3. Apply a condition or transformation

  4. Append the new value to the list

values = [1, 2, 3, 4, 5]
even_values = []

for v in values:
    if v % 2 == 0:
        even_values.append(v)

This pattern is correct, explicit, and used constantly. List comprehension exists specifically because this pattern is so common that Python created a shortcut for it.

A refinement, not a replacement

List comprehension:

  • does not replace for loops entirely

  • does not introduce new computational behavior

  • simply shortens a well-understood pattern

You should always be able to rewrite a list comprehension as a normal for loop, and vice versa.


2. The basic structure

One loop in one expression

The simplest form of a list comprehension squashes the loop and the append action into a single line wrapped in square brackets [].

[new_value for item in collection]
Syntax breakdown of a basic list comprehension showing the expression, loop variable, and collection.

Every list comprehension requires these three core parts wrapped in square brackets: the output expression, the loop variable, and the collection to iterate over.

Example:

values = [2, 4, 6]
squared = [v**2 for v in values]

To read this easily, read the middle first, then the left:

“For every v in values, take v ** 2 and put it in a new list.”

Relation to a for loop

The following two blocks do the exact same thing:

# Standard Loop
cubed = []
for v in values:
    cubed.append(v**3)
# List Comprehension
cubed = [v**3 for v in values]

The logic is identical. Only the form is different.


3. Filtering values with conditions

Adding an if clause at the end

List comprehensions can also include a condition to filter out unwanted data. When filtering, the if statement goes at the very end of the expression.

[new_value for item in collection if condition]
Syntax breakdown of a list comprehension with an if-condition at the end for filtering.

When filtering data, the if condition always acts as a gatekeeper at the very end of the expression.

Example:

values = [1, 2, 3, 4, 5]
even_values = [v for v in values if v % 2 == 0]

Only values that satisfy the condition (v % 2 == 0) are allowed into the new list.

Example: Valid environmental measurements

temperatures = [3, -5, 7, 42, 9]
valid = [t for t in temperatures if -20 <= t <= 40]

This expresses a data quality filter cleanly in just one line.


4. Transforming values

Changing values while building the list

The “expression” part at the front of the list comprehension doesn’t just have to be the variable itself; it can be a mathematical transformation.

values = [1, 2, 3]
doubled = [v * 2 for v in values]

Example: Unit conversion

temperatures_c = [0, 5, 10, 15]
temperatures_k = [t + 273.15 for t in temperatures_c]

This is a clean, Pythonic way to express a systematic transformation of spatial or environmental data.


5. If–else inside list comprehension

Conditional transformation (Choosing between two values)

Sometimes you don’t want to drop a value completely (filtering), but rather change it based on a condition.

If you need an if-else decision, the syntax changes. The entire if-else block must move to the beginning of the comprehension, before the for loop.

[value_if_true if condition else value_if_false for item in collection]
Syntax breakdown of a list comprehension showing an if-else conditional expression placed at the beginning before the for loop.

When transforming data conditionally, the entire if-else logic becomes the “output expression” and must be placed at the very beginning of the brackets.

Example:

values = [3, -1, 5, -2]
labels = ["valid" if v >= 0 else "invalid" for v in values]
# Output: ['valid', 'invalid', 'valid', 'invalid']

Read this as:

“Put ‘valid’ if v is >= 0, else put ‘invalid’... do this for every v in values.”

Readability rule

The syntax for if-else inside a list comprehension can get visually messy very quickly.


6. When to use list comprehension

Good use cases

List comprehensions work beautifully when:

  • building a new list from an old one

  • applying a simple mathematical transformation

  • filtering values based on a single condition

  • the logic fits comfortably and readably on one line

When not to use it

Avoid list comprehension when:

  • the logic involves complex nested loops

  • you need multiple elif conditions

  • you are updating external variables or printing

  • readability suffers

In those cases, stick to a normal for loop.


7. Exercises

The following exercises help you practice reading, writing, and deciding when list comprehension is appropriate.

Focus on clarity first, compactness second.


Exercise 1: Rewrite a loop as list comprehension

You are given the following loop:

rainfall = [0, 5, 12, 0, 8, 20]
non_zero = []

for r in rainfall:
    if r > 0:
        non_zero.append(r)

Rewrite this using one list comprehension.



Exercise 2: Transform values with context

You are working with elevation values in meters:

elevation_m = [450, 1200, 50, 3200]

Create a new list that converts these values to kilometres and rounds them to one decimal place. You can use Python’s built-in round() function for this, which takes the number to round and the desired number of decimal places (e.g., round(value, 1)).



Exercise 3: Classify measurements

Given temperature measurements:

temperatures = [-5, 3, 18, -12, 25]

Create a list of labels:

  • "cold" for values below 0

  • "warm" for values 0 or above

Use one list comprehension with if–else.




8. Summary

Key ideas

  • List comprehension is a compact loop pattern used strictly for building new lists.

  • It combines looping, filtering, and transformation into one line.

  • The if goes at the end when filtering data.

  • The if-else goes at the beginning when transforming data conditionally.

  • It improves clarity only when used carefully. If it is hard to read, use a standard loop.


Choosing the right loop

for loop           → “Repeat an action for each value.”
while loop         → “Repeat an action until a condition changes.”
list comprehension → “Build a new list from existing data.”

What comes next

In the upcoming practical exercises, you will combine everything from this module to:

  • process small environmental datasets using loops and conditions

  • detect invalid values and thresholds

  • write clean, Pythonic data structures for later analysis