Skip to content

Q&A · Answered

How to use list comprehensions in Python

asked 9 months, 1 week ago 1726 views 1 answer
26

I keep seeing list comprehensions in Python code. Can you explain how to use them effectively?

1 Answer

One accepted
13

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago

Basic list comprehension

# Instead of loop
squares = []
for x in range(10):
    squares.append(x ** 2)

# Use list comprehension
squares = [x ** 2 for x in range(10)]

With conditions

# Filter even numbers
evens = [x for x in range(20) if x % 2 == 0]

# Conditional expression
result = [x if x > 0 else 0 for x in numbers]

# Nested comprehension
matrix = [[i*j for j in range(5)] for i in range(5)]

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.