surprising += for lists
d at davea.name
Sun Nov 4 13:45:45 CET 2012
On 11/04/2012 06:57 AM, Ulrich Eckhardt wrote:
> Hi everybody!
> I was just smacked by some very surprising Python 2.7 behaviour. I was
> assembling some 2D points into a list:
> points = 
> points += (3, 5)
> points += (4, 6)
> What I would have expected is to have [(3, 5), (4, 6)], instead I got [3,
> 5, 4, 6].
is equivalent to mylist.extend. And as you say, what you wanted was
> My interpretations thereof is that the tuple (x, y) is iterable,
You're confusing cause and effect. If it weren't iterable, it'd be an
error. It would NOT just somehow change to be equivalent to append.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
> so the elements are appended one after the other. Actually, I should have
> used points.append(), but that's a different issue.
> Now, what really struck me was the fact that  + (3, 5) will give me a
> type error. Here I wonder why the augmented assignment behaves so much
What I wonder about is why list's __add__ is so fussy.
> Can anyone help me understand this?
I'd also point out that when using the extend() function call, we'd have
to spell it:
The extra parentheses are to make it clear to the compiler that this is
a single argument, a tuple, and not two arguments.
to get your original desired behavior.
More information about the Python-list