473,766 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.?)

Oct 17 '07 #1
10 15028
On Wed, 17 Oct 2007 20:27:14 +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)
This is a bad idea as it creates a useless list of `None`\s, one for each
element in `b`.
How do I do this using a list comprehension?
Not at all. The obvious solution here is ``a.extend(b)`` .
(In general, is using a list comprehension preferable (or more
"pythonic") as opposed to using map / filter etc.?)
Some say yes.

Ciao,
Marc 'BlackJack' Rintsch
Oct 17 '07 #2
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 Haese
http://informixdb.sourceforge.net
Oct 17 '07 #3
On Oct 17, 9:27 pm, Debajit Adhikary <debaj...@gmail .comwrote:
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.appen d, b)
[None, None, None]
>>a
[1, 2, 3, 4, 5, 6]

HTH

--
Paul Hankin

Oct 17 '07 #4
On Oct 17, 10:03 pm, Debajit Adhikary <debaj...@gmail .comwrote:
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.
Anyway, look at 'timeit' to see how to measure things like this, but
my advice would be not to worry and to write the most readable code -
and only optimise if your code's runnign too slowly.

To answer your question though: a += b is *not* the same as a = a + b.
The latter would create a new list and assign it to a, whereas a += b
updates a in-place.

--
Paul Hankin

Oct 17 '07 #5
On Wed, 17 Oct 2007 21:40:40 +0000, Paul Hankin wrote:
On Oct 17, 10:03 pm, Debajit Adhikary <debaj...@gmail .comwrote:
>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.
Neither am I. Why do you say that?

Anyway, look at 'timeit' to see how to measure things like this, but my
advice would be not to worry and to write the most readable code - and
only optimise if your code's runnign too slowly.
Always good advice, but of course what a person considers "the most
readable code" changes with their experience.

To answer your question though: a += b is *not* the same as a = a + b.

It might be. It depends on what a and b are.

--
Steven
Oct 18 '07 #6
Paul Hankin <pa*********@gm ail.comwrites:
On Oct 17, 10:03 pm, Debajit Adhikary <debaj...@gmail .comwrote:
>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 +=.
Oct 18 '07 #7
On Oct 18, 10:21 am, Hrvoje Niksic <hnik...@xemacs .orgwrote:
Paul Hankin <paul.han...@gm ail.comwrites:
On Oct 17, 10:03 pm, Debajit Adhikary <debaj...@gmail .comwrote:
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

Oct 18 '07 #8
Debajit Adhikary a écrit :
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)
And what about a.extend(b) ?
How do I do this using a list comprehension?
Why would you want a list comp here ???
(In general, is using a list comprehension preferable (or more
"pythonic") as opposed to using map / filter etc.?)
Depends. Anyway, the pythonic solution here is to use the appropriate
list method !-)

Oct 18 '07 #9
Paul Hankin <pa*********@gm ail.comwrites:
Not to me: I can never remember which of a.append and a.extend is
which.
Interesting, with me it's the other way around. Maybe it's because I
used Python before extend was available.
Falling back to a = a + b is exactly what you want.
Not if you want to mutate the original object, possibly referenced
from elsewhere.
Oct 18 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
35478
by: christof hoeke | last post by:
hello, this must have come up before, so i am already sorry for asking but a quick googling did not give me any answer. i have a list from which i want a simpler list without the duplicates an easy but somehow contrived solution would be >>> a = >>> d = {}.fromkeys(a) >>> b = d.keys()
35
2981
by: Moosebumps | last post by:
Does anyone here find the list comprehension syntax awkward? I like it because it is an expression rather than a series of statements, but it is a little harder to maintain it seems. e.g. you could do: result = for element in list: if element == 'blah':
0
1725
by: William Park | last post by:
1. Here is shell version of Python filter() for array. Essentially, you apply a command on each array element, and extract only those elements which it returns success (0). This is specialized form of list comprehension where you can contruct an array from another array, using some sort of test or filtering. Usage is arrayfilter command array where 'command' is a function, shell script, or external executable, which takes one...
24
3356
by: Mahesh Padmanabhan | last post by:
Hi, When list comprehension was added to the language, I had a lot of trouble understanding it but now that I am familiar with it, I am not sure how I programmed in Python without it. Now I see that generator expressions have been added to the language with 2.4 and I question the need for it. I know that it allows for lazy evaluation which speeds things up for larger lists but why was it necessary to add it instead of improving list...
1
2302
by: Ron Adam | last post by:
In my program I have a lot of statements that append elements, but sometimes I don't want to append the element so it requres an if statement to check it, and that requires assigning the returned element from a function to a name or calling the funtion twice. e = ET.Element('name') e.append(get_subelement(obj)) # but raises an exception on None
7
7658
by: greenflame | last post by:
I am trying to reorder elements of a list and I am stuck as to what might be the best way to approach this. I have a (main) list of elements and another (ordering) list (which is may shorter, but not longer than the main list) which contains the order in which I want the elements of the main list but only as far along as the length of the ordering list. This may be confusing so I will try to give an example. Suppose the main list is:...
18
460
by: a | last post by:
can someone tell me how to use them thanks
4
1812
by: Gregory Guthrie | last post by:
Sorry for a simple question- but I don't understand how to parse this use of a list comprehension. The "or" clauses are odd to me. It also seems like it is being overly clever (?) in using a lc expression as a for loop to drive the recursion. Thanks for any insight! Gregory
33
1720
by: John Salerno | last post by:
Is it possible to write a list comprehension for this so as to produce a list of two-item tuples? base_scores = range(8, 19) score_costs = print zip(base_scores, score_costs) I can't think of how the structure of the list comprehension would work in this case, because it seems to require iteration over two separate sequences to produce each item in the tuple.
0
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9404
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10009
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8835
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5279
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.