473,699 Members | 2,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

'while' in list comprehension?

Hi there,

wouldn't it be useful to have a 'while' conditional in addition to
'if' in list comprehensions?

foo = []
for i in bar:
if len(i) == 0:
break
foo.append(i)

would then turn into

foo = [ i for i in bar while len(i)>0 ]

Is there any reason for not having this kind of thing? I actually
miss it pretty often.

Cheers, jsaul
Jul 18 '05 #1
14 15231
jsaul asks...
would then turn into

foo = [ i for i in bar while len(i)>0 ]

Is there any reason for not having this kind of thing? I actually
miss it pretty often.

How is this different from:

foo = [ i for i in bar if len(i) ]

Emile van Sebille
em***@fenx.com
Jul 18 '05 #2
foo = [ i for i in bar while len(i)>0 ]


Emile> How is this different from:

Emile> foo = [ i for i in bar if len(i) ]

The first is like:

_ = []
for i in bar:
if not (len(i) > 0):
break
_.append(i)
return _

The second is like:

_ = []
for i in bar:
if len(i) > 0:
_.append(i)
return _

Skip

Jul 18 '05 #3
Use 2.3's itertools:
foo = [i for i in itertools.takew hile(lambda i: len(i) > 0, bar)]
or maybe
foo = list(itertools. takewhile(len, bar)]
or even
foo = itertools.takew hile(len, bar) # an iterable, not a list

Jeff

Jul 18 '05 #4
At 01:05 PM 10/22/2003, Emile van Sebille wrote:
jsaul asks...
would then turn into

foo = [ i for i in bar while len(i)>0 ]

Is there any reason for not having this kind of thing? I actually
miss it pretty often.

How is this different from:

foo = [ i for i in bar if len(i) ]


My reading is that the comprehension would stop at the first i whose len
were 0. e.g.
foo = []
for i in bar:
if len(i) == 0:break
foo.append(i)

Bob Gailer
bg*****@alum.rp i.edu
303 442 2625
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.525 / Virus Database: 322 - Release Date: 10/9/2003

Jul 18 '05 #5
"Emile van Sebille" <em***@fenx.com > wrote in message
news:bn******** ****@ID-11957.news.uni-berlin.de...
jsaul asks...
would then turn into

foo = [ i for i in bar while len(i)>0 ]

Is there any reason for not having this kind of thing? I actually
miss it pretty often.

How is this different from:

foo = [ i for i in bar if len(i) ]

Emile van Sebille
em***@fenx.com


The idea is that 'while' stops iterating through the list when the condition
isn't met. 'if' just doesn't output anything. e.g.:
bar = ['this', 'is', 'a', 'list', '', 'see?']
[i for i in bar if len(i)] ['this', 'is', 'a', 'list', 'see?'] [i for i in bar while len(i)] # Pretend

['this', 'is', 'a', 'list']

What's your typical use for this?

I guess I see nothing really wrong with it, although I thought list
comprehensions were supposed to make the iteration transparent--'while'
kinda destroys the illusion. But these are the only two looping constructs
that make sense in a list comprehension, so why not support both? OTOH,
'while' makes no sense in a dictionary comprehension (and presumably we'll
have those one day.)

Jul 18 '05 #6
jsaul <js***@gmx.de > wrote in message news:<20******* *************@j saul.de>...

foo = [ i for i in bar while len(i)>0 ]

Is there any reason for not having this kind of thing? I actually
miss it pretty often.


Could you provide an example where you need it?

From your message, it seems "bar" might be a list of strings. If so, you could use:

foo = bar[:bar.index('')]

regards,

Hung Jung
Jul 18 '05 #7

"jsaul" <js***@gmx.de > wrote in message
news:20******** ************@js aul.de...
Hi there,

wouldn't it be useful to have a 'while' conditional in addition to
'if' in list comprehensions?

foo = []
for i in bar:
if len(i) == 0:
break
foo.append(i)

would then turn into

foo = [ i for i in bar while len(i)>0 ]


while is simply not same as if: break!
if executes once for each value of i, while indefinitely.
If you translate back by current rule, which will not change, you get:

foo = []
for i in bar:
while len(i) >0:
foo.append(i)

Terry J. Reedy
Jul 18 '05 #8
On Wed, 22 Oct 2003 22:57:42 -0400, "Terry Reedy" <tj*****@udel.e du>
wrote:
while is simply not same as if: break!
if executes once for each value of i, while indefinitely.
If you translate back by current rule, which will not change, you get:


'while' is an English word which has meaning independant of the
existing Python 'while' loop. It is not necessarily wrong to apply a
different aspect of that meaning in a list comprehension.

Besides, I read the syntax as equating to...

foo = []
for i in bar while len(i) >0:
foo.append(i)

Yes, I know that isn't a legal Python loop. My point is that it didn't
look like a nested loop to me, but rather like an additional qualifier
on the existing loop.

That said, you do have a point - multiple 'for' parts in a list
comprehension act as nested loops, so maybe a while part should too.

The trouble is that a standalone while loop probably makes little
sense in a list comprehension - sure you have a place to put the loop
condition, but what about the initialisation and body?

If there were a real while-part in a list comprehension, it would
probably need those things to become explicit (becoming a lot like the
C for loop) - something like...

[k while k=1; k<1024; k*=2]

Hmmmm...

while i=0; i<10; i++ :
print i

Hmmmm....

Nah - damn silly idea.
--
Steve Horne

steve at ninereeds dot fsnet dot co dot uk
Jul 18 '05 #9
* Terry Reedy [2003-10-23 04:57]:
"jsaul" <js***@gmx.de > wrote in message
news:20******** ************@js aul.de...
wouldn't it be useful to have a 'while' conditional in addition to
'if' in list comprehensions?

foo = []
for i in bar:
if len(i) == 0:
break
foo.append(i)

would then turn into

foo = [ i for i in bar while len(i)>0 ]


while is simply not same as if: break!
if executes once for each value of i, while indefinitely.
If you translate back by current rule, which will not change, you get:

foo = []
for i in bar:
while len(i) >0:
foo.append(i)


I agree that 'while' cannot not just be considered a replacement
for 'if'. However, adding a 'while' conditional to list
comprehensions would very unlikely be misunderstood as another
(infinite) loop. Instead, I find the above 'while' example about
as intuitive as is the case with 'if'. It simply means that under
a certain condition the loop will be ended, which is just what
most people would probably expect.

Anyway, thanks a lot to all who replied! What is your opinion
after this discussion, write a PEP or just forget about it?

Cheers, jsaul
Jul 18 '05 #10

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

Similar topics

23
40630
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
2968
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
2269
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
1977
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=]
21
1827
by: Daniel Schüle | last post by:
Hello NG, I am wondering if there were proposals or previous disscussions in this NG considering using 'while' in comprehension lists # pseudo code i=2 lst= of course this could be easily rewritten into
18
460
by: a | last post by:
can someone tell me how to use them thanks
4
1809
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
12
1723
by: Eighty | last post by:
I suggest a new extension of the list comprehension syntax: which would be equivalent to list(itertools.takewhile(cond, xs)) + Since Python favors list comprehensions over map, filter, and reduce, this would be the preferred way to do this
10
15021
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 =
0
9174
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9034
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...
0
8883
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
7750
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...
0
5874
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();...
0
4376
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
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2009
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.