DEV Community
•
2026-04-20 02:59
Write a List in One Line (List Comprehensions)
You have been building lists the long way.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = []
for n in numbers:
squares.append(n * n)
print(squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Four lines. A variable, a loop, an operation, an append. This works perfectly. Nothing wrong with it.
But Python has a shorter way. One line instead of four.
numbers = [1, ...