Python Gotcha's?
John Posner
jjposner at optimum.net
Thu Apr 5 10:15:03 EDT 2012
On 4/4/2012 7:32 PM, Chris Angelico wrote:
> Don't know if it's what's meant on that page by the += operator,
Yes, it is.
>> a=([1],)
>> a[0].append(2) # This is fine
[In the following, I use the term "name" rather loosely.]
The append() method attempts to modify the object whose name is "a[0]".
That object is a LIST, so the attempt succeeds.
>> a[0]+=[3] # This is not.
The assignment attempts to modify the object whose name is "a". That
object is a TUPLE, so the attempt fails. This might be a surprise, but
I'm not sure it deserves to be called a wart.
Note the similarity to:
temp = a[0] + [3] # succeeds
a[0] = temp # fails
-John
More information about the Python-list
mailing list