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, 2, 3, 4, 5, 6, 7,
Write a List in One Line (List Comprehensions)
Akhilesh·Dev.to··1 min read
D
Continue reading on Dev.to
This article was sourced from Dev.to's RSS feed. Visit the original for the complete story.