Originally published on CodingCush .
A list comprehension is a short, readable way to build a new list in Python in a single line. Instead of writing a loop that starts with an empty list and appends one item at a time, you describe the list you want β the expression, the loop and an optional condition β inside square brackets, and Python builds it for you.
The Loop You Already Know, Written Shorter
Every list comprehension starts life as an ordinary loop, so let us begin with the loop version. Suppose you want the squares of the numbers from 1 to 5. The traditional way takes three honest lines, and there is absolutely nothing wrong with it:
squares = [] for n in range(1, 6): squares.append(n * n)
print(squares) # [1, 4, 9, 16, 25]
Enter fullscreen mode
Exit fullscreen mode
Now watch the same job collapse into one line that says exactly the same thing, in almost the same order as you would say it out loud β the squares of each n, for each n in the range:
squares = [n * n for n in range(1,β¦