nigel222 nigel222 - 3 months ago 9
Python Question

Why do Python lists have an extend method?

What does

a_list.extend(list2)
do (or do better) that
a_list += list2
doesn't?

That's all really, except to observe that it would have been an answer if
.extend()
returned the extended list so you could cascade another method. But it doesn't, so you can't.

Answer

list.extend() is an expression and can be embedded in larger expressions. += (augmented assignment) is a statement, and statements can never be embedded in expressions.

So you can do this:

doubled_extender = lambda l, it: l.extend(v for v in it for _ in range(2))

but you can't use += there.

Note that for list objects, the object.__iadd__() special method that += uses, calls list.extend() directly before returning self.

Last but not least, the Augmented Assignments feature was added to the language later than list.extend().