Using a List Comprehension

List comprehension in Python is a compact way to create new lists by transforming or filtering items from an existing one. It lets you write in one readable line what would normally take several lines of a loop.

A list comprehension looks like this:

list comprehension syntax

Simple Example

Example of list comprehension

Adding a Condition

You can filter items using an if clause:

Example of list comprehension with a condition

This creates a list of only the numbers that satisfy the condition.

Same thing using a for loop:

Example showing how the previous list comprehension would be built in a common for loop

Nested Loops with List Comprehension

You can also nested loops:

Example of list comprehension with nested loops

Quick Summary

List comprehension is a concise way to build lists using a loop, optional filtering, and an expression.

Web developers love it because it is short and clean. It removes unnecessary loops and reads easily like a sentence.

Although my blog doesn’t support comments, feel free to reply via email or X.