Functions and objects

Paul Magwene paul.magwene at yale.edu
Tue Apr 11 16:06:41 EDT 2000


Matthew Hirsch wrote:
> 
> Hi All,
> 
> I'm confused.  Take a look at the following:
> 
> >>> def f(x):
> ...     return [x]
> ...
> >>> a=f(5)
> >>> a
> [5]
> >>> for x in range(5):     # Case A
> ...     temp=a
> ...     print a
> ...     temp.append(1)
> ...
> [5]
> [5, 1]
> [5, 1, 1]
> [5, 1, 1, 1]
> [5, 1, 1, 1, 1]
> 
> >>> a=f(5)
> >>> for x in range(5):     # Case B
> ...     temp=a[:]
> ...     print a
> ...     temp.append(1)
> ...
> [5]
> [5]
> [5]
> [5]
> [5]
> >>>
> 
> In case A, why doesn't temp reset itself to the value of a, [5], that
> was predetermined before it entered the loop?  Why do you need to copy
> the list to get the behavior I'm looking for in Case B?  Doesn't a
> always equal [5]?
> 
> Thanks for your help,
> Matt

Matthew,

Many of your questions to the group are addressed in the tutorial and/or
FAQ.  Obviously people in this newsgroup are glad to offer help and
information, but it's always a good idea to try and track down your own
sources of info first.

You question in this case is addressed in the Python tutorial, sections
4.6 and 4.7 (and footnote 4.1).

In a Python function, what gets passed to the function is an object
reference.  

Assignment always stores a reference to an object, it DOES NOT make a
copy of the object. 

The object you are passing in both cases is a list, therefore mutable. 
In case A, the assignment temp = a, is equivalent to sticking a new
"label" on your mutable list object.  Then your appending stuff to this
object (called either "a" or "temp").  In case B, your are generating a
new copy of a list object, and calling this new object "temp". 
Therefore, modifying the "temp" object has no bearing on the "a" object.

If you are going to do a significant amount of Python programming it
might be useful to acquire one of the several available python texts. 
Learning Python, by Lutz and Ascher is a good one to start.

Best,

Paul



More information about the Python-list mailing list