Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

for loop with transformation

There are many cases when we have a list of some values and we need to apply some transformation to each value. At the end we would like to have the list of the resulting values.

A very simple such transformation would be to double each value. Other, more interesting examples might be reversing each string, computing some more complex function on each number, etc.)

In this example we just double the values and use append to add each value to the list containing the results.

def double(n):
    return 2 * n

numbers = [7, 2, 4, 1]

double_numbers = []
for num in numbers:
    double_numbers.append( double(num) )
print(double_numbers)

Output:

[14, 4, 8, 2]

There are better ways to do this.