Python

Python List Comprehensions

The Problem List Comprehensions Solve

A very common pattern is building a new list by transforming or filtering an existing one. The traditional loop version:

numbers = [1, 2, 3, 4, 5] squares = [] for n in numbers: squares.append(n ** 2)

The Comprehension Version

A list comprehension does the same thing in a single, readable line:

numbers = [1, 2, 3, 4, 5] squares = [n ** 2 for n in numbers] print(squares) # [1, 4, 9, 16, 25]

Adding a Condition

You can filter items with an if clause at the end:

evens = [n for n in range(20) if n % 2 == 0] print(evens) # [0, 2, 4, 6, ...]

If/Else Inside a Comprehension

When you need a value for every item (not just filtering), put the if/else before the loop:

labels = ["even" if n % 2 == 0 else "odd" for n in range(5)] print(labels) # ['even', 'odd', 'even', 'odd', 'even']

Dictionary and Set Comprehensions

The same syntax works with {} for dictionaries and sets:

squares_dict = {n: n ** 2 for n in range(5)} unique_lengths = {len(word) for word in ["hi", "hey", "hello"]}

When Not to Use Them

If the logic needs more than one condition or transformation step, a regular loop is usually more readable. Comprehensions are for simple, single-purpose transformations — not everything.

Practice Exercise

Given a list of words, write a comprehension that returns only the words longer than 4 characters, in uppercase.

Leave a Reply

Your email address will not be published. Required fields are marked *