How to use list comprehensions in Python

Answered
Jan 05, 2026 1307 views 1 answers
26

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

D
Asked by db_admin
Silver 415 rep

1 Answer

13

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)]
D
Answered by devops_guru 1 week, 2 days ago
Gold 290 rep

Your Answer

You need to be logged in to answer questions.

Log In to Answer

Related Questions

Hot Questions

No hot questions available.