[Tutor] Multiple for and if/else statements into a single list comprehension

spir denis.spir at gmail.com
Mon Mar 17 13:36:01 CET 2014


On 03/17/2014 11:22 AM, Jignesh Sutar wrote:
> Is it possible to get two nested for statements followed by a nested
> if/else statement all into a single list comprehension ie. the equivalent
> of the below:
>
>
> for i in xrange(1,20):
>      for j in xrange(1,10):
>          if j<6:
>              j=int("8"+str(j))
>          else:
>              j=int("9"+str(j))
>          print "%(i)02d_%(j)02d" % locals()

You can do it by reformulating your inner block into an expression (here, using 
a ternary if expression), which will then become the expression part of the 
comprehension. However, a few remarks:

* don't do that: the only advantage is to make your code unreadable
* you may reformulate using 2 comprehensions; if you don't want intermediate 
lists, use a generator expression for the inner one
* above, the inner j is a new variable with a distinct meaning: why do you call 
it j?
* do you really need string concat to perform arithmetic?

d


More information about the Tutor mailing list