[Python-ideas] if-statement in for-loop

Nick Coghlan ncoghlan at gmail.com
Tue Sep 27 11:33:54 EDT 2016


On 28 September 2016 at 00:55, Erik Bray <erik.m.bray at gmail.com> wrote:
> On Sun, Sep 11, 2016 at 12:28 PM, Bernardo Sulzbach
> <mafagafogigante at gmail.com> wrote:
>> On 09/11/2016 06:36 AM, Dominik Gresch wrote:
>>>
>>> So I asked myself if a syntax as follows would be possible:
>>>
>>> for i in range(10) if i != 5:
>>>     body
>>>
>>> Personally, I find this extremely intuitive since this kind of
>>> if-statement is already present in list comprehensions.
>>>
>>> What is your opinion on this? Sorry if this has been discussed before --
>>> I didn't find anything in the archives.
>>>
>>
>> I find it interesting.
>>
>> I thing that this will likely take up too many columns in more convoluted
>> loops such as
>>
>>     for element in collection if is_pretty_enough(element) and ...:
>>         ...
>>
>> However, this "problem" is already faced by list comprehensions, so it is
>> not a strong argument against your idea.
>
> Sorry to re-raise this thread--I'm inclined to agree that the case
> doesn't really warrant new syntax.  I just wanted to add that I think
> the very fact that this syntax is supported by list comprehensions is
> an argument *in its favor*.
>
> I could easily see a Python newbie being confused that they can write
> "for x in y if z" inside a list comprehension, but not in a bare
> for-statement.  Sure they'd learn quickly enough that the filtering
> syntax is unique to list comprehensions.  But to anyone who doesn't
> know the historical progression of the Python language that would seem
> highly arbitrary and incongruous I would think.
>
> Just $0.02 USD from a pedagogical perspective.

This has come up before, and it's considered a teaching moment
regarding how the comprehension syntax actually works: it's an
*arbitrarily deep* nested chain of if statements and for statements.

That is:

  [f(x,y,z) for x in seq1 if p1(x) for y in seq2 if p2(y) for z in
seq3 if p3(z)]

can be translated mechanically to the equivalent nested statements
(with the only difference being that the loop variable leak due to the
missing implicit scope):

    result = []
    for x in seq1:
        if p1(x):
            for y in seq2:
                if p2(y):
                    for z in seq3:
                        if p3(z):
                            result.append(f(x, y, z))

So while the *most common* cases are a single for loop (map
equivalent), or a single for loop and a single if statement (filter
equivalent), they're not only the forms folks may encounter in the
wild.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list