a.extend(b) better than a+=b ?
Peter Otten
__peter__ at web.de
Thu Apr 22 09:28:32 CEST 2010
candide wrote:
> Suppose a and b are lists.
>
> What is more efficient in order to extend the list a by appending all
> the items in the list b ?
>
>
> I imagine a.extend(b)to be more efficient for only appendinding the
> items from b while a+=b creates a copy of a before appending, right ?
No. Both append items to the original list a:
>>> a = original_a = [1,2,3]
>>> a.extend([4,5,6])
>>> a is original_a # you knew that
True
>>> a += [7,8,9] # could rebind a
>>> a is original_a # but effectively doesn't for lists
True
(Strictly speaking a += [...] rebinds a to the same value, like a = a)
It is mostly a matter of personal preference which form you use.
I prefer the extend() method because I think it's clearer; you don't run the
risk of mistaking it for an arithmetic operation.
Peter
PS: an example where += does rebind:
>>> a = original_a = (1,2,3)
>>> a += (4,5,6)
>>> a is original_a
False
More information about the Python-list
mailing list