conditional for-statement

Discussion in 'Python' started by seb, Aug 23, 2009.

  1. seb

    seb Guest

    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
    seb, Aug 23, 2009
    #1
    1. Advertising

  2. seb <sdementen <at> gmail.com> writes:

    >
    > Hi,
    >
    > i was wondering if there is a syntax alike:
    >
    > for i in range(10) if i > 5:
    > print i


    for i in range(10):
    if i > 5:
    print i
    Benjamin Peterson, Aug 23, 2009
    #2
    1. Advertising

  3. On Aug 23, 10:09 am, seb <> wrote:
    > 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
    ----
    FB
    Francesco Bochicchio, Aug 23, 2009
    #3
  4. 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
    Bruno Desthuilliers, Aug 24, 2009
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Anand P Paralkar
    Replies:
    2
    Views:
    9,358
    Srinivasan Venkataramanan
    Aug 4, 2003
  2. Erica
    Replies:
    3
    Views:
    1,331
    The Dead Bishop
    Jul 18, 2004
  3. Replies:
    3
    Views:
    791
  4. Giorgio
    Replies:
    1
    Views:
    3,036
    Eliyahu Goldin
    Jul 21, 2005
  5. Alec S.
    Replies:
    10
    Views:
    10,095
    Alec S.
    Apr 16, 2005
Loading...

Share This Page