4.1 Back to the Basics

Assignment
Assignment would seem to be the most elementary programming concept, not deserv
ing a separate discussion. However, there are some surprising subtleties here. Consider
the following code fragment:

foo = ‘Monty’
bar = foo
foo = ‘Python’
bar
‘Monty’
This behaves exactly as expected. When we write bar = foo in the code
, the value
of foo (the string ‘Monty’) is assigned to bar. That is, bar is a copy of foo, so when we
overwrite foo with a new string ‘Python’ on line , the value of bar is not affected.
However, assignment statements do not always involve making copies in this way.
Assignment always copies the value of an expression, but a value is not always what
you might expect it to be. In particular, the “value” of a structured object such as a list
is actually just a reference to the object. In the following example, assigns the refer
ence of foo to the new variable bar. Now when we modify something inside foo on line
, we can see that the contents of bar have also been changed.

foo = [‘Monty’, ‘Python’]
bar = foo
foo[1] = ‘Bodkin’
bar
[‘Monty’, ‘Bodkin’]
The line bar = foo does not copy the contents of the variable, only its “object refer
ence.” To understand what is going on here, we need to know how lists are stored in
the computer’s memory. In Figure 4-1, we see that a list foo is a reference to an object
stored at location 3133 (which is itself a series of pointers to other locations holding
strings). When we assign bar = foo, it is just the object reference 3133 that gets copied.
This behavior extends to other aspects of the language, such as parameter passing

Leave a Reply