Functions and objects

Gordon McMillan gmcm at hypernet.com
Tue Apr 11 15:45:49 EDT 2000


Matthew Hirsch wrote:

> >>> 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]?

In case A, temp is another name for a. In B, temp is a copy of 
a. The existence of "f" has nothing to do with it.

- Gordon




More information about the Python-list mailing list