473,388 Members | 1,524 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 software developers and data experts.

"For" loop and list comprehension similarity

Hi All,

I apologize if this was brought up before, I couldn't find any "prior
art" :-).
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if <test>:
print i*2

....because it's similar to the list comprehension construct:

[i*2 for i in c if <test>]
---------

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

for i in c:
if <test>:
print i*2

Just curious. Thanks!

Sergey.

Mar 26 '06 #1
10 1625
s.*********@gmail.com wrote:
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if <test>:
print i*2
Maybe there's been a PEP, don't really know...
Currently, the only sensible alternative is what you've written below:
The available equivalent
feels a bit awkward:

for i in c:
if <test>:
print i*2

This indeed doesn't look nice, especially if you've got lots of code instead of just
print. An alternative which avoids double indentation is

for i in c:
if not <test>: continue
print i*2
Mar 26 '06 #2
Thank you for replying, Mitja! That *is* a nice alternative.

Do you think it's a good idea to ask on comp.python.devel if they would
be interested in a PEP about this (provided there is none)?

Cheers,
Sergey.

Mar 26 '06 #3
On 2006-03-26, s.*********@gmail.com <s.*********@gmail.com> wrote:
Hi All,

I apologize if this was brought up before, I couldn't find any "prior
art" :-).
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if <test>:
print i*2

...because it's similar to the list comprehension construct:

[i*2 for i in c if <test>]
---------

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

for i in c:
if <test>:
print i*2


for j in [i*2 for i in c if <test>]:
print j

--
Grant Edwards grante Yow! .. I wonder if I
at ought to tell them about my
visi.com PREVIOUS LIFE as a COMPLETE
STRANGER?
Mar 26 '06 #4
s.*********@gmail.com writes:
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if <test>:
print i*2

...because it's similar to the list comprehension construct:

[i*2 for i in c if <test>]


Why not combine the two:

for i in [j for j in c if <test>]:
print i*2

--
\ "I got food poisoning today. I don't know when I'll use it." |
`\ -- Steven Wright |
_o__) |
Ben Finney

Mar 26 '06 #5
> Why not combine the two:

I guess because (at least in source code) you're doing a loop twice
:-). I don't know what a compiler would do. I think though that the
"for i in c if test:" construct is more readable and maybe can even be
better optimized.
Thanks!

Sergey.

Mar 26 '06 #6
Rather than a list comprehension, it would be faster and more
memory-efficient to use a generator comprehension. Just change the
square brackets to parentheses:

for j in (i*2 for i in c if <test>):
print j
Grant Edwards wrote:
On 2006-03-26, s.*********@gmail.com <s.*********@gmail.com> wrote:
Hi All,

I apologize if this was brought up before, I couldn't find any "prior
art" :-).
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if <test>:
print i*2

...because it's similar to the list comprehension construct:

[i*2 for i in c if <test>]
---------

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

for i in c:
if <test>:
print i*2

for j in [i*2 for i in c if <test>]:
print j

Mar 26 '06 #7

<s.*********@gmail.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
Why not combine the two:


I guess because (at least in source code) you're doing a loop twice
:-). I don't know what a compiler would do. I think though that the
"for i in c if test:" construct is more readable and maybe can even be
better optimized.


There are also the filter and ifilter functions:

for i in filter(testfunc, c):

tjr

Mar 27 '06 #8
I think I like generator comprehension in this case better than either
list comprehension or a filter because both of the latter create a new
full "result list" before the loop even begins. At least I suppose they
do. Also, I think Mitja's suggestion "if not <test>: continue" and
Terry's filter function are more readable than comprehensions.
It's not a contest though :-), all these variants are great, thank you
all!
Do you think this discussion is a proof that the following principle
got violated, or do you think that "loop with condition" is not such an
atomic thing to be subject to this: "There should be one -- and
preferably only one -- obvious way to do it."
Cheers,

Sergey.

Mar 27 '06 #9
s.*********@gmail.com wrote:
Do you think this discussion is a proof that the following principle
got violated, or do you think that "loop with condition" is not such an
atomic thing to be subject to this: "There should be one -- and
preferably only one -- obvious way to do it."


Mitja's suggestion was the one obvious way. The others are all
interesting, maybe even preferable in some cases, but I don't think most
experienced Python programmers would be more likely to start with one of
them than with the simple for-loop-with-explicit-test.

-Peter

Mar 27 '06 #10

"Peter Hansen" <pe***@engcorp.com> wrote in message
news:e0**********@sea.gmane.org...
s.*********@gmail.com wrote:
Do you think this discussion is a proof that the following principle
got violated, or do you think that "loop with condition" is not such an
atomic thing to be subject to this: "There should be one -- and
preferably only one -- obvious way to do it."


Mitja's suggestion was the one obvious way. The others are all
interesting, maybe even preferable in some cases, but I don't think most
experienced Python programmers would be more likely to start with one of
them than with the simple for-loop-with-explicit-test.


If by 'explicit-test' you mean a nested if-statement, then I agree. When I
mentioned filter() as one way to avoid the obvious, I was aware that it
creates an intermediate list that is usually not needed. (And if it is
needed, then it should be name-assigned before the loop.)

Terry Jan Reedy

Mar 27 '06 #11

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

Similar topics

23
by: Invalid User | last post by:
While trying to print a none empty list, I accidentaly put an "else" statement with a "for" instead of "if". Here is what I had: if ( len(mylist)> 0) : for x,y in mylist: print x,y else:...
11
by: David Morgenthaler | last post by:
How does one overide the iterator implied by the construct "for line in file:"? For example, suppose I have a file containing row,col pairs on each line, and I wish to write a subclass of file...
32
by: Toby Newman | last post by:
At the page: http://www.strath.ac.uk/IT/Docs/Ccourse/subsection3_8_3.html#SECTION0008300000000000000 or http://tinyurl.com/4ptzs the author warns: "The for loop is frequently used, usually...
3
by: songie D | last post by:
would it be possible to sort of engineer some sort of preprocessor macro that does a 'for' loop. i.e. for where you would normally use a normal for loop, but when it is known ay compile time whay...
4
by: Jacob Rael | last post by:
I am new to python and I love it. I am hacking a file. I want to not print a line if it contains the word 'pmos4_highv'. I also don't want to print the next line. The following code works but it...
34
by: Frederick Gotham | last post by:
Is the domestic usage of the C "for" loop inefficient when it comes to simple incrementation? Here's a very simple program that prints out the bit-numbers in a byte. #include <stdio.h> #include...
15
by: Steve | last post by:
I am having problems getting values out of an array. The array is set as a global array and values are pushed into it as they are read from a JSON file using a "for loop". When the "for loop" is...
8
by: Ratko | last post by:
Say you have something like this: for item in myList: del item Would this actually delete the item from the list or just decrement the reference counter because the item in myList is not...
9
by: Alexnb | last post by:
Okay, so lets say you have a list: funList = and you do: for x in funList: print x this will print 1-5
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.