Appending a list's elements to another list using a list comprehension
Paul Hankin
paul.hankin at gmail.com
Wed Oct 17 16:46:43 EDT 2007
On Oct 17, 9:27 pm, Debajit Adhikary <debaj... at gmail.com> 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?
>
> (In general, is using a list comprehension preferable (or more
> "pythonic") as opposed to using map / filter etc.?)
Yes, using a list comprehension is usually more pythonic than using
map/filter. But here, the right answer is:
a.extend(b). The first thing you should always do is check the python
libraries for a function or method that does what you want. Even if
you think you know the library quite well it's still worth checking:
I've lost count of the number of times I've discovered a library
function that does exactly what I wanted.
Anyway, if extend didn't exist, the pythonic version of map(a.append,
b) would be
for x in b:
a.append(x)
Rather than
[a.append(x) for x in b]
List comprehensions and map produce a new list. That's not what you
want here: you're using the side-effect of the append method - which
modifies a. This makes using regular iteration the right idea, because
by using map or a comprehension, you're also constructing a list of
the return values of append (which is always None). You can see this
in the interpreter:
>>> map(a.append, b)
[None, None, None]
>>> a
[1, 2, 3, 4, 5, 6]
HTH
--
Paul Hankin
More information about the Python-list
mailing list