Functions and objects

Matthew Hirsch meh9 at cornell.edu
Tue Apr 11 15:25:50 EDT 2000


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



More information about the Python-list mailing list