List Comprehension: Compact List Building
Published:
• Last updated:
• By Jeferson Peter
Python
why use list comprehension
- Fewer lines than traditional loops
- Easier to read once you get familiar
- Often more efficient for simple operations
example generate squares
using a loop
squares = []
for i in range(1, 6):
squares.append(i * i)
print(squares)
using comprehension
squares = [i * i for i in range(1, 6)]
print(squares)
[1, 4, 9, 16, 25]
with conditions
evens = [i for i in range(10) if i % 2 == 0]
print(evens)
[0, 2, 4, 6, 8]
conclusion
Comprehensions are useful when they keep the transformation simple and obvious. Prefer loops if the logic grows complex.