Python Gotcha's?
Robert Kern
robert.kern at gmail.com
Thu Apr 5 10:45:57 EDT 2012
On 4/5/12 3:15 PM, John Posner wrote:
> 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.
The wart is not that it fails, but that it does not fail atomically. The list
inside the tuple gets modified even though an exception is raised for the
statement as a whole.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list