nigel222 nigel222 - 1 year ago 81
Python Question

Why do Python lists have an extend method?

What does

do (or do better) that
a_list += list2

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

Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download