Sponsored Reserved space — layout preview until AdSense is connected

List comprehension filter

Build a new list in one line by filtering and transforming items.

7 lines 4 views 0 copies Updated May 23, 2026
Try in editor

How it works

List comprehensions combine a for loop and optional if filter inside square brackets.

They read best when the expression is short — for heavy logic, a plain loop is clearer.

This sample keeps even numbers and doubles them in a single readable expression.

Python
Try in editor
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
doubled_evens = [n * 2 for n in numbers if n % 2 == 0]
print(doubled_evens)

names = ["ada", "linus", "guido"]
title_case = [name.title() for name in names if name]
print(title_case)

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops