[Python-ideas] if in for-loop statement
Henk-Jaap Wagenaar
wagenaarhenkjaap at gmail.com
Thu Feb 23 08:37:15 EST 2017
Hi all,
Often I have typed something like
for x in range(100) if is_prime(x):
# do things with x
to find that this does not work, instead resorting to:
for x in range(100):
if is_prime(x):
# do things with x
or
for x in range(100):
if not is_prime(x):
continue
# do things with x
Other solutions to another case of this 'problem' are discussed has been
discussed on StackOverflow (
http://stackoverflow.com/questions/6981717/pythonic-way-to-combine-for-loop-and-if-statement)
where it is suggested one uses a generator expression before the loop. None
of these solutions seem very Pythonic to me.
I appreciate there is a cost associated with changing the language syntax,
and I do not understand all the finer details of the inner workings
involved with the Python language development, however in my limited
understanding in it would be:
- fully backwards compatible,
- require one to change "expression_list" to "or_test [comp_iter]" in the
syntax of the for statement (if I got it right).
- it would mean there is a Pythonic solution to a current 'problem' that
does not have one.
A few problems I foresee:
- One wants for loops to bleed their target_list (that is the point
normally), so this is different from generators,
- This allows for nesting of generators, like in a generator expression
which might be hard to implement?
Note that this has been suggested before at least once (
https://mail.python.org/pipermail/python-dev/2007-November/075257.html),
and that thread itself suggests it has been suggested before and shutdown
by Guido (though no source is given for this).
All the best,
Henk-Jaap Wagenaar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170223/6d152c97/attachment.html>
More information about the Python-ideas
mailing list