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

Erik Bray erik.m.bray at gmail.com
Tue Sep 27 10:55:00 EDT 2016


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.

Erik


More information about the Python-ideas mailing list