PythoneasyPython

List Comprehension with Filter

Filter and transform lists in one elegant line using comprehensions.

01

The problem

You want to filter a list and optionally transform the remaining items efficiently.

02

The solution

Python
# Basic filter
evens = [x for x in numbers if x % 2 == 0]

# Filter and transform
squared_evens = [x ** 2 for x in numbers if x % 2 == 0]

# With function call
valid_emails = [email.lower() for email in emails if '@' in email]

# Nested comprehension (flatten)
flattened = [item for sublist in matrix for item in sublist]

# Dictionary comprehension
word_lengths = {word: len(word) for word in words if len(word) > 3}

03

Put it to work

Example
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get squares of even numbers
result = [x ** 2 for x in numbers if x % 2 == 0]
print(result)  # [4, 16, 36, 64, 100]

# Filter users by age
users = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 17}]
adults = [u['name'] for u in users if u['age'] >= 18]
print(adults)  # ['Alice']

Worth knowing

List comprehensions are faster than equivalent for loops. Keep them readable - use regular loops for complex logic.