Extending a list in #Python

>>> a = []
>>> a.extend([2, 1]) # neat
>>> a += [3, 4] # hmm ok
>>> a += (7, 11) # huh?
>>> a[-1:] += [18, 29] # uh oh
>>> a[:] = [*a, 47, 76] # 😦
>>> a
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]

#pythonoddity

@treyhunner Yeah, the implicit conversion of tuples to lists gets me sometimes. I wish I could turn it off.
@kevin @treyhunner It has nothing to do with touples, and it's not conversion - the operator is implemented so that it works with any iterable.

@b11c @kevin

true, but only for lists!

>>> a = [1, 2]
>>> b = (3, 4)
>>> a += b
>>> b += a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple

The list += operator was made consistent with the list extend method.

But other sequences, both mutable and immutable, typically allow only the same type with +=.

I explain it in my Python Oddities talk here: https://youtu.be/nWC73Llo170?t=735

Talk - Trey Hunner: Python Oddities Explained

YouTube