Python Gotcha's?
Michael Hrivnak
mhrivnak at hrivnak.org
Thu Apr 5 14:44:16 EDT 2012
This is not a gotcha, and it's not surprising. As John described,
you're assigning a new value to an index of a tuple, which tuples
don't support.
a[0] += [3]
is the same as
a[0] = a[0] + [3]
which after evaluation is the same as
a[0] = [1, 3]
You can always modify an item that happens to be in a tuple if the
item itself is mutable, but you cannot add, remove, or replace items
in a tuple.
Michael
On Thu, Apr 5, 2012 at 10:15 AM, John Posner <jjposner at optimum.net> 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.
>
> Note the similarity to:
>
> temp = a[0] + [3] # succeeds
> a[0] = temp # fails
>
> -John
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list