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

Bernardo Sulzbach mafagafogigante at gmail.com
Sun Sep 11 06:28:58 EDT 2016


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.

I am still unsure about whether or not the pattern you describe is 
frequent enough to justify special syntax. Not to mention that the 
current way to do it is already **very** readable. Just notice how

     for e in l:
         if e != 2:
             ...

and

     for e in l if e != 2:
             ...

read essentially the same and take about the same number of keystrokes.


More information about the Python-ideas mailing list