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

Paul Hankin paul.hankin at gmail.com
Thu Oct 18 07:57:10 EDT 2007


On Oct 18, 10:21 am, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> Paul Hankin <paul.han... at gmail.com> writes:
> > On Oct 17, 10:03 pm, Debajit Adhikary <debaj... at gmail.com> wrote:
> >> How does "a.extend(b)" compare with "a += b" when it comes to
> >> performance? Does a + b create a completely new list that it assigns
> >> back to a? If so, a.extend(b) would seem to be faster. How could I
> >> verify things like these?
>
> > Use a += b rather than a.extend(b): I'm not sure what I was
> > thinking.
>
> Why?  a.extend(b) is at least as readable, and is guaranteed to extend
> the same list.  In general, "a += b" can fall back to the slower "a =
> a + b" for sequences that don't support +=.

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 +=.

--
Paul Hankin




More information about the Python-list mailing list