December 2017
Beginner to intermediate
410 pages
12h 45m
English
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)
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 ...