Functions and objects

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Tue Apr 11 15:48:03 EDT 2000


Matthew Hirsch wrote in comp.lang.python:
> >>> a
> [5]

a is now a name for that list [5].

> >>> for x in range(5):     # Case A
> ...     temp=a

Now, temp is another name for the same object. a en temp are the same list.

> ...     print a
> ...     temp.append(1)

This appends to that list in place. a and temp are still just different
names for the same list, so they both point to the changed list.

> ... 
> [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[:]

Here, temp is a copy of a, so now temp and a are two distinct lists, with
the same value ([5]). 

> ...     print a
> ...     temp.append(1)

Temp is changed, but since that was not the same object as a anyway, a isn't
affected.

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

No. Assignment in Python always works by reference. This is one of the key
features of Python that you need to grok.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
'Oook?'



More information about the Python-list mailing list