On this page

List Comprehensions

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

What List Comprehensions Are​

A list comprehension is a compact, expressive syntax for creating lists.

It replaces many common for‑loop patterns with a single, readable expression.

General form:


[new_item for item in iterable]

This is equivalent to:


result = []

for item in iterable:

    result.append(new_item)

List comprehensions are faster, cleaner, and more Pythonic.


Basic Transformation​

Transform each element of a list:


numbers = [1, 2, 3, 4]

squares = [n * 2 for n in numbers]

Result:


[2, 4, 6, 8]

This is the most common use case: mapping one list to another.


Filtering with Conditions​

Add an if clause to include only certain elements.


numbers = [1, 2, 3, 4, 5, 6]

evens = [n for n in numbers if n % 2 == 0]

Result:


[2, 4, 6]

This replaces a loop with an if inside it.


Transform + Filter Together​

You can combine both operations:


squares_of_evens = [n*n for n in numbers if n % 2 == 0]

This is a powerful pattern for data processing.


Using Expressions Inside Comprehensions​

Any expression can be used:


words = ["hello", "python", "world"]

uppercased = [w.upper() for w in words]

Or even method calls:


cleaned = [w.strip() for w in words]

Nested Loops​

List comprehensions can include multiple for loops.

Example: flatten a 2D list.


matrix = [[1, 2], [3, 4], [5, 6]]

flat = [num for row in matrix for num in row]

Equivalent to nested loops, but more concise.


Conditional Expressions (Inline if/else)​

Use an inline conditional to transform values differently:


labels = ["even" if n % 2 == 0 else "odd" for n in numbers]

This is different from filtering:

every element is included, but transformed conditionally.


List Comprehensions vs. Loops​

List comprehensions are ideal when:

Use a normal loop when:

Good Python code prioritizes clarity over cleverness.


Common Use Cases​

These patterns appear constantly in real‑world Python.


Best Practices​

Readable code is always better than clever code.


Summary​

In this lesson, you learned how list comprehensions provide a concise, expressive way to build lists. You explored transformations, filtering, inline conditionals, nested loops, and best practices.

List comprehensions are a core Python skill that dramatically improves the clarity and efficiency of your code.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Intermediate Python & Best Practices

Next

Generators