10.19. Pure Functions

A pure function does not produce side effects. It communicates with the calling program only through parameters (which it does not modify) and a return value. Here is the doubleStuff function from the previous section written as a pure function. To use the pure function version of double_stuff to modify things, you would assign the return value back to things.

 
1
def doubleStuff(a_list):
2
    """ Return a new list in which contains doubles of the elements in a_list. """
3
    new_list = []
4
    for value in a_list:
5
        new_elem = 2 * value
6
        new_list.append(new_elem)
7
    return new_list
8
9
things = [2, 5, 9]
10
print(things)
11
things = doubleStuff(things)
12
print(things)
13

(ch09_mod2)

Once again, codelens helps us to see the actual references and objects as they are passed and returned.

Python 2.7
1def doubleStuff(a_list):
2    """ Return a new list in which contains doubles of the elements in a_list. """
3    new_list = []
4    for value in a_list:
5        new_elem = 2 * value
6        new_list.append(new_elem)
7    return new_list
8
9things = [2, 5, 9]
10things = doubleStuff(things)
Step 1 of 17
line that has just executed

next line to execute

Visualized using Online Python Tutor by Philip Guo
Frames
Objects

(ch09_mod3)

Next Section - 10.20. Which is Better?