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

Debajit Adhikary debajit1 at gmail.com
Wed Oct 17 17:03:56 EDT 2007


On Oct 17, 4:41 pm, Carsten Haese <cars... at uniqsys.com> wrote:
> On Wed, 2007-10-17 at 20:27 +0000, Debajit Adhikary wrote:
> > I have two lists:
>
> > a = [1, 2, 3]
> > b = [4, 5, 6]
>
> > What I'd like to do is append all of the elements of b at the end of
> > a, so that a looks like:
>
> > a = [1, 2, 3, 4, 5, 6]
>
> > I can do this using
>
> > map(a.append, b)
>
> > How do I do this using a list comprehension?
>
> You don't.
>
> > (In general, is using a list comprehension preferable (or more
> > "pythonic") as opposed to using map / filter etc.?)
>
> In general, a list comprehension is more Pythonic nowadays, but in your
> particular case the answer is neither map nor a list comprehension, it's
> this:
>
> a += b
>
> HTH,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

Thanks a ton :)

What in general is a good way to learn about little things like these?
(I'm fairly new to the language)

A google search for 'python list methods" did not turn up the +
operator anywhere for me. Where could I find the official
documentation for built in structures like the list? (I just noticed
that the + operator for lists is mentioned in Beazley's Python
Essential Reference -- in the opening pages, which I didn't look at
when I was writing the earlier code.)

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?




More information about the Python-list mailing list