26
I keep seeing list comprehensions in Python code. Can you explain how to use them effectively?
Loading...
Q&A · Answered
I keep seeing list comprehensions in Python code. Can you explain how to use them effectively?
Accepted answer
# Instead of loop
squares = []
for x in range(10):
squares.append(x ** 2)
# Use list comprehension
squares = [x ** 2 for x in range(10)]
# 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)]Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.