Appending a list's elements to another list using a list comprehension

J. Clifford Dyer jcd at sdf.lonestar.org
Thu Oct 18 08:58:37 EDT 2007


On Thu, Oct 18, 2007 at 11:57:10AM -0000, Paul Hankin wrote regarding Re: Appending a list's elements to another list using a list comprehension:
> 
> Not to me: I can never remember which of a.append and a.extend is
> which. Falling back to a = a + b is exactly what you want. For
> instance:
> 
> a = (1, 2, 3)
> a += (4, 5, 6)
> 
> works, whereas:
> 
> a = (1, 2, 3)
> a.extend((4, 5, 6))
> 
> doesn't. So using += makes your code more general. There's no standard
> sequence type that has extend and not +=, so worrying that += is
> slower isn't a concern unless you're using a user-defined class. Even
> then, it's probably a mistake that should be fixed in the class rather
> than requiring .extend() to be used instead of +=.
> 

I was going to argue that in fact += is not more general, it just covers a different set of use cases, but then I tested my hypothesis...

>>> a = [1,2,3]
>>> b = a
>>> c = [4,5,6]
>>> d = c
>>> e = [7,8,9]
>>> a.extend(e)
>>> b
[1, 2, 3, 7, 8, 9]
>>> c += e
>>> d # I expected [4, 5, 6]
[4, 5, 6, 7, 8, 9]
>>> c = c + e # But += doesn't do the same as this
>>> c
[4, 5, 6, 7, 8, 9, 7, 8, 9]
>>> d
[4, 5, 6, 7, 8, 9]

So I learned something new.

Cheers,
Cliff



More information about the Python-list mailing list