On Aug 25, 11:57 pm, Piet van Oostrum <p...@cs.uu.nl> wrote: > You can also say: > [x+y for x in range(3) for y in range(4) if x < y] > If you want to write this as a loop you have to put the for's on > separate lines separated by colons, so why not the if also? Or would you > also like to have the for's on one line?
indeed, we could have the for's on one line too. In fact, if you have a double loop without any body that is specific to the outer loop, you can merge the two lines. Similarly, if you have a loop with a if (ie filter) without any body having to be executed outside the if, having them on the same line is also clearer. | for x in range(3): | for x in range(3) for y in range(4): | for y in range(4): could be written as | body | body and | for x in range(3): | for x in range(3) if cond(x): | if cond(x): could be written as | body | body Such loops are in fact mentally just one loop over the cartesian product (product set) of the two iterators or over the filter set of the iterator respectively in these examples. Moreover, for 'body' longer than a couple of lines, it is quite useful to see immediately that there is no additional code that could be only specific to the outher loop ie, when writing all in one line, we can be sure that we do not have this situation | for x in range(3): | for y in range(4): | long body | ... | long body | body related to outer loop The naturalness of iteration in the various comprehensions and the generator expressions can be smoothly extended to the standard code iteration. BTW, I noticed this inconsistency when, coming back to python after a couple of weeks of no python programming, I started coding loops like for obj in list_obj if obj.Size > 100: print(obj) and got an error message about syntax. > -- > Piet van Oostrum <p...@cs.uu.nl> > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p...@vanoostrum.org- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list