Functions and objects
Mark Hathaway
hathawa2 at marshall.edu
Tue Apr 11 21:10:52 EDT 2000
>> Matthew wrote:
>>
>> I'm confused. Take a look at the following:
a = [5]
>> for x in range(5): # Case A
>> temp=a
>> print a
>> temp.append(1)
print temp # to see what's happening to it
>> [5]
>> [5, 1]
>> [5, 1, 1]
>> [5, 1, 1, 1]
>> [5, 1, 1, 1, 1]
a = [5]
>> for x in range(5): # Case B
>> temp=a[:]
>> print a
>> temp.append(1)
print temp # to see what's happening to it
>> [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]?
> Assignment always stores a reference to an object, it DOES NOT make a
> copy of the object.
It doesn't default to making a copy. you have to specify if you want a
copy!
So,
temp = a
isn't the same as
temp = a[:]
The first copies the address, stored as a simple variable in a, which
points to the object [5]
The second doesn't copy the address, it creates a new object with a copy
of what a pointed to.
This is one of the oddities (IMO) of Python.
It's about like saying temp = a[:] is temp = newOjbect([5])
wheras temp = a is temp = addressOf([5])
I know it was all simple when you could write (in most languages)
a = 5
temp = a
and temp is a new separate different variable with a value of 5.
That's not quite what's happening in Python. Study the difference
carefully.
Mark S. Hathaway
email: hathawa2 at marshall.edu
More information about the Python-list
mailing list