Sponsored Reserved space — layout preview until AdSense is connected
Python list comprehensions — filter and transform in one line

Tutorial

Python list comprehensions — filter and transform in one line

Learn list comprehension syntax with filters, nested loops, and readable alternatives to manual for-loops.

March 2026 · 7 min read · 8 views · 2 hearts

Why comprehensions matter

In Python you often build a new list by looping over something else: maybe you transform each item, skip some items, or both. A list comprehension expresses that pattern in one readable expression instead of writing several lines of boilerplate.

Basic syntax

The core shape is:

[expression for item in iterable]

For example, double every number:

nums = [1, 2, 3, 4]
doubled = [n * 2 for n in nums]
print(doubled)

Adding a filter

Put an if clause at the end to keep only items that match a condition. This is usually clearer than a manual loop with .append inside an if.

values = range(12)
only_even_squares = [x * x for x in values if x % 2 == 0]
print(only_even_squares)

Nested loops (use sparingly)

Comprehensions support multiple for parts. That power is easy to abuse — if readability drops, switch back to nested loops or helper functions.

# Coordinate pairs where x != y on a tiny grid
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]
print(len(pairs), "pairs")

When not to use them

  • Very heavy per-item logic — prefer a named function and a plain loop.
  • Multiple side effects — comprehensions should stay expression-focused.
  • Deep nesting — flatten your design instead of chaining many fors.

Next step

Use Try in editor above to run the bundled sample (filters + nested comprehension). Edit the lists and conditions, press Run, and watch how output changes — same workflow as classic tutorial sandboxes.

Comments

Questions, corrections, and tips stay visible for everyone reading this page.

0 in thread

Join the discussion

Shown next to your comment.

Constructive tone · up to 4,000 characters

No comments yet

Be the first to leave a note — it helps the next reader.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected