473,811 Members | 2,485 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can this be done with list comprehension?

This is what I'm trying to do (create a list using list comprehesion, then
insert new element at the beginning of that list):

result = [someFunction(i) for i in some_list].insert(0, 'something')

But instead of expected results, I get None as `result`. If instead of
calling `insert` method I try to index the list like this:

result = [someFunction(i) for i in some_list][0]

It works as expected. Am I doing something wrong, or I can't call list
methods when doing list comprehension?

P.S.
In case you're wondering, it has to be done in one line ;).
--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____ |_____|
Jun 27 '08 #1
7 910
Karlo Lozovina wrote:
This is what I'm trying to do (create a list using list comprehesion, then
insert new element at the beginning of that list):

result = [someFunction(i) for i in some_list].insert(0, 'something')

But instead of expected results, I get None as `result`. If instead of
calling `insert` method I try to index the list like this:

result = [someFunction(i) for i in some_list][0]

It works as expected. Am I doing something wrong, or I can't call list
methods when doing list comprehension?
The problem is that list methods like insert do not return a list --
they modify it in place. If you do
a = [1,2,3]
a.insert(0, 'something')
then a will have the results you expect, but if you do
b = a.insert(0,'som ething')
you will find b to be None (although a will have the expected list).

P.S.
In case you're wondering, it has to be done in one line ;).
Jun 27 '08 #2
Gary Herron <gh*****@island training.comwro te in
news:ma******** *************** **************@ python.org:
The problem is that list methods like insert do not return a list --
they modify it in place. If you do
a = [1,2,3]
a.insert(0, 'something')
then a will have the results you expect, but if you do
b = a.insert(0,'som ething')
you will find b to be None (although a will have the expected list).
I figured that out few minutes ago, such a newbie mistake :). The fix I
came up with is:

result = ['something'] + [someMethod(i) for i in some_list]

Are there any other alternatives to this approach?

--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____ |_____|
Jun 27 '08 #3
On Jun 8, 8:31 am, Karlo Lozovina <_karlo_@_mosor .net_wrote:
This is what I'm trying to do (create a list using list comprehesion, then
insert new element at the beginning of that list):

result = [someFunction(i) for i in some_list].insert(0, 'something')
result = ['something'] + [someFunction(i) for i in some_list]
Jun 27 '08 #4

"Karlo Lozovina" <_karlo_@_mosor .net_wrote in message
news:Xn******** *************@1 61.53.160.64...
| I figured that out few minutes ago, such a newbie mistake :). The fix I
| came up with is:
|
| result = ['something'] + [someMethod(i) for i in some_list]
|
| Are there any other alternatives to this approach?

result = [something]
result.extend(s omeMethod(i) for i in some_list)

avoids creating and deleting an intermediate list

Jun 27 '08 #5
Lie
On Jun 8, 7:27*am, "Terry Reedy" <tjre...@udel.e duwrote:
"Karlo Lozovina" <_karlo_@_mosor .net_wrote in message

news:Xn******** *************@1 61.53.160.64...
| I figured that out few minutes ago, such a newbie mistake :). The fix I
| came up with is:
|
| *result = ['something'] + [someMethod(i) for i in some_list]
|
| Are there any other alternatives to this approach?

result = [something]
result.extend(s omeMethod(i) for i in some_list)

avoids creating and deleting an intermediate list
or:
result = ['something'].extend(someMet hod(i) for i in some_list)

it also avoids intermediate list and is one line.
Jun 27 '08 #6
Lie <Li******@gmail .comwrote:
On Jun 8, 7:27*am, "Terry Reedy" <tjre...@udel.e duwrote:
>"Karlo Lozovina" <_karlo_@_mosor .net_wrote in message

news:Xn******* **************@ 161.53.160.64.. .
| I figured that out few minutes ago, such a newbie mistake :). The
| fix I came up with is:
|
| *result = ['something'] + [someMethod(i) for i in some_list]
|
| Are there any other alternatives to this approach?

result = [something]
result.extend( someMethod(i) for i in some_list)

avoids creating and deleting an intermediate list

or:
result = ['something'].extend(someMet hod(i) for i in some_list)

it also avoids intermediate list and is one line.
and also throws the list away as soon as it creates it. Didn't you read
earlier in this thread: list methods that mutate the list in-place return
None.
Jun 27 '08 #7
Le Sunday 08 June 2008 02:27:54 Terry Reedy, vous avez écrit*:
"Karlo Lozovina" <_karlo_@_mosor .net_wrote in message
news:Xn******** *************@1 61.53.160.64...

| I figured that out few minutes ago, such a newbie mistake :). The fix I
| came up with is:
|
| result = ['something'] + [someMethod(i) for i in some_list]
|
| Are there any other alternatives to this approach?

result = [something]
result.extend(s omeMethod(i) for i in some_list)

avoids creating and deleting an intermediate list

--
http://mail.python.org/mailman/listinfo/python-list
A one liner, though it's a bit lispy :

list(itertools. chain((somethin g,), (someMethod(i) for i in some_list)))

--
_____________

Maric Michaud
Jun 27 '08 #8

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

Similar topics

23
40656
by: Fuzzyman | last post by:
Pythons internal 'pointers' system is certainly causing me a few headaches..... When I want to copy the contents of a variable I find it impossible to know whether I've copied the contents *or* just created a new pointer to the original value.... For example I wanted to initialize a list of empty lists.... a=, , , , ] I thought there has to be a *really* easy way of doing it - after a
35
3002
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':
7
2280
by: Chris P. | last post by:
Hi. I've made a program that logs onto a telnet server, enters a command, and then creates a list of useful information out of the information that is dumped to the screen as a result of the command. Here's a generic version of the code in question: ##### # Prior code opens telnet connection "tn" and logs in. tn.read_until('> ') tn.write('THE COMMAND IS HERE\n')
6
1990
by: jena | last post by:
hello, when i create list of lambdas: l=] then l() returns 'C', i think, it should be 'A' my workaround is to define helper class with __call__ method: class X: def __init__(self,s): self.s=s def __call__(self): return self.s.upper() l=]
18
460
by: a | last post by:
can someone tell me how to use them thanks
4
1815
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
4
1572
by: bullockbefriending bard | last post by:
Given: class Z(object): various defs, etc. class ZList(list): various defs, etc. i would like to be able to replace
10
15036
by: Debajit Adhikary | last post by:
I have two lists: a = b = 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 =
4
3059
by: beginner | last post by:
Hi All, If I have a list comprehension: ab= c = "ABC" print c
0
9728
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
9605
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
10389
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
10402
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
10135
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9205
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
7670
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
6890
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3867
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.