A typical task in Python is to iterate over a list, run some function on each value, and save the results into a new list.
# create a list
l = [1, 2, 3, 4, 5]
# list of newly calculated results
r = []
# iterate over the list
for i in l:
# square each number and add the new value to a new list
r.append(i ** 2)
print(r)
[1, 4, 9, 16, 25]
Unfortunately, this approach requires a few lines of code to do a relatively simple task. One way to rewrite this loop more compactly is by using a Python list comprehension. This shortcut offers a concise way of performing the same action.
# note the square brackets around on the right-hand side
# this saves the final results as a list
rc = [i ** 2 for i in l]
print(rc)
[1, 4, 9, 16, 25]
print(type(rc))
<class 'list'>
Our final results will be a list, so the right-hand side will have a pair of square brackets. From there, we write what looks very similar to a for
loop. Starting from the center and moving toward the right side, we write for i in l
, which is very similar to the first line of our original for
loop. On the right side, we write i
**
2
, which is similar to the body of the for
loop. Since we are using a list comprehension, we no longer need to specify the list to which we want to append our new values.
3.22.41.235