Python Basics

Python List Comprehensions with Examples

Replace a four-line loop with one readable line that transforms and filters a list.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • The [expression for item in iterable] form
  • Filtering with if
  • Dict and set comprehensions
[n * n for n in range(1, 11) if n % 2 == 0]
  1. 1for n in range(1, 11)Take each number
  2. 2if n % 2 == 0Keep the even ones
  3. 3n * nSquare them
  4. 4[4, 16, 36, 64, 100]Collect the results

Loop, filter and result in one expression

The problem

A very common task is building a new list from an old one: square every number, keep only the passing scores, clean every name. With a normal loop that takes four lines and an empty list to start with, and the intent gets lost in the details.

Think of it like this

A list comprehension is like a sorting conveyor in a factory. Items move along the belt one by one, a gate lets through only the ones that pass a check, and a machine changes each item that passes before it drops into a new box.

From a factory belt to code
for number in numbers🏭 Items move along the belt
if number % 2 == 0🚦 The gate lets only even numbers through
number ** 2⚙️ The machine squares each one
[...]📦 Everything lands in a new box (list)
Loop, filter and change in one line; the original list is untouched.
In one sentence

A list comprehension builds a new list in one expression: [result for item in items if condition].

Key points

  1. numbers = range(1, 11) gives the numbers 1 to 10.
  2. for number in numbers goes through them; if number % 2 == 0 keeps only the even ones.
  3. number ** 2 is applied to each number that passed the filter.
  4. The result is a brand-new list; numbers is not changed.

When should you use it?

  • Transforming every item: prices with tax, names in upper case, lengths of words.
  • Filtering: passing scores, non-empty lines, files with a given extension.
  • Doing both in one readable line when the rule is simple.

When not to use it

  • The logic needs several steps, nested conditions or try / except: a normal loop is clearer.
  • You only need the total or the count: sum() or a generator avoids building a list.

See how it works

Press Step to send each number through the condition and the expression. Change the condition or the expression to build another list.

Example code

Run code →
main.py
numbers = range(1, 11)
even_squares = [number ** 2 for number in numbers if number % 2 == 0]

print(even_squares)
Get a Run button for this example

Result of running the code

[4, 16, 36, 64, 100]

Code explanation

The comprehension reads from left to right like a sentence: square the number, for each number in numbers, if the number is even. Python checks the condition first and only squares the values that pass, so the result holds the squares of 2, 4, 6, 8 and 10. numbers itself is left as it was.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Common mistakes

Putting the condition in the wrong place

A filter goes at the end. A value that depends on a condition uses if ... else before for.

Problem
[number ** 2 if number % 2 == 0 for number in numbers]
Fix
[number ** 2 for number in numbers if number % 2 == 0]

Squeezing too much into one line

If you need comments to explain the comprehension, a loop is easier to read.

Problem
[x * y for x in a if x for y in b if y % x and y > 2]
Fix
result = []
for x in a:
    for y in b:
        if x and y % x and y > 2:
            result.append(x * y)

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges