conditional for-statement

S

seb

Hi,

i was wondering if there is a syntax alike:

for i in range(10) if i > 5:
print i

equivalent to

for i in (for i in range(10) if i>5):
print i

sebastien
 
F

Francesco Bochicchio

Hi,

i was wondering if there is a syntax alike:

for i in range(10) if i > 5:
    print i

equivalent to

for i in (for i in range(10) if i>5):
    print i

sebastien

AFAIK, no syntax fo that. But the standard syntax is not too
different:

for i in range(0):
if i > 5 : print i

Or you can use itertools.ifilter:

for i in itertools.ifilter( lambda x: x > 5, range(10) ):
print i

Or, if you define a function corresponding to the loop body, you could
do something like:

map( print, (i for i in range(10) if i> 5 )) # only works if print is
a function



Ciao
 
B

Bruno Desthuilliers

seb a écrit :
Hi,

i was wondering if there is a syntax alike:

for i in range(10) if i > 5:
print i

equivalent to

for i in (for i in range(10) if i>5):
print i

what about :

for i in range(6, 10):
print i

<g>


More seriously:

for i in range(10):
if i > 5:
print i
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top