Changing a mutable affects the caller

This is the final point, and it's very important because Python apparently behaves differently with mutables (just apparently, though). Let's look at an example:

# key.points.mutable.py
x = [1, 2, 3]
def func(x):
x[1] = 42 # this affects the caller!

func(x)
print(x) # prints: [1, 42, 3]

Wow, we actually changed the original object! If you think about it, there is nothing weird in this behavior. The x name in the function is set to point to the caller object by the function call and within the body of the function, we're not changing x, in that we're not changing its reference, or, in other words, we are not changing the object x is pointing to. We're accessing that object's element at position 1, and changing its value.

Remember point #2 under the Input parameters section: Assigning an object to an argument name within a function doesn't affect the caller. If that is clear to you, the following code should not be surprising:

# key.points.mutable.assignment.py
x = [1, 2, 3]
def func(x):
x[1] = 42 # this changes the caller!
x = 'something else' # this points x to a new string object

func(x)
print(x) # still prints: [1, 42, 3]

Take a look at the two lines I have highlighted. At first, like before, we just access the caller object again, at position 1, and change its value to number 42. Then, we reassign x to point to the 'something else' string. This leaves the caller unaltered and, in fact, the output is the same as that of the previous snippet.

Take your time to play around with this concept, and experiment with prints and calls to the id function until everything is clear in your mind. This is one of the key aspects of Python and it must be very clear, otherwise you risk introducing subtle bugs into your code. Once again, the Python Tutor website (http://www.pythontutor.com/) will help you a lot by giving you a visual representation of these concepts.

Now that we have a good understanding of input parameters and how they behave, let's see how we can specify them.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.42.196