[Python-ideas] for-loop-if like list comps have?

Andrew Barnert abarnert at yahoo.com
Sun Mar 30 23:12:42 CEST 2014


From: Christopher Welborn <cjwelborn at live.com>

> On 03/30/2014 05:44 AM, Liam Marsh wrote:
>>  hello,
>>  is it possible to accept this syntax?
>>  it is about the same subject, but an other proposition...
>>  so, here it is:
>> 
>>   >>>for x in xs , y in ys:
>>  ... � �***instructions***
>>  thank you!

(This is obviously a reply to Liam, not Christopher.)


It's not clear which of these you want that to mean:

    for x, y in zip(xs, ys):
        do_stuff(x, y)

    for x, y in product(xs, ys):
        do_stuff(x, y)

And the existing versions are already pretty clear and readable.

In a listcomp, it's often clearer to use two for clauses than product… but usually in that case you write them on separate lines, and in a statement, it would be even clearer to use nested statements. Compare this somewhat realistic use case:

    transformed_values = (long expression with value and sublist
                          for sublist in long_function_that_returns_a_list(various, arguments)
                          for value in sublist)

    for sublist in long_function_that_returns_a_list(various, arguments):
        for value in sublist:
            yield long expression with value and sublist

Would you really want to write the second one on one line, even if you could?

    for sublist in long_function_that_returns_a_list(various, arguments), value in sublist:
        yield long expression with value and sublist


More information about the Python-ideas mailing list