surprising += for lists

Ulrich Eckhardt doomster at knuut.de
Sun Nov 4 12:57:56 CET 2012


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]. My interpretations thereof is that the tuple (x, y) is 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 
different.

Can anyone help me understand this?

Thanks!

Uli





More information about the Python-list mailing list