In Java, we can have a FOR loop like this
for (i = 0; i < 10; i += 1) {
}
Yet this is not possible in Python; FOR can only be used in the "foreach" sense, looping through each element in an iterable.
Why were the control structures for the FOR loop left out in Python?
The Zen of Python says “There should be one-- and preferably only one --obvious way to do it.” Python already has this way to do it:
for i in xrange(10):
pass
If you want to make all the parts explicit, you can do that too:
for i in xrange(0, 10, 1):
pass
Since it already has an “obvious” way to do it, adding another way would be un-zen. (Would that be “nez”?)
(Note: In Python 3, use range
instead of xrange
.)
A C-style for
loop has more flexibility, but ultimately you can write an equivalent loop with Python's while
(or C's while
for that matter), which touches not only on the “one obvious way” principle, but also “Simple is better than complex” amongst others. This is all a matter of taste, of course—in this case, Guido van Rossum's taste.
Since this is one of those questions that goes back to the mists of Python 0.x (in fact, most likely to its predecessor ABC), the only person who can really answer is Guido, and then only if he remembers. You could try asking him to write a post on his History of Python blog.
However, there are some good reasons for this.
First, having only a single form of for
instead of two different forms makes the language smaller—simpler to learn and read for humans, and simpler to parse for computers.
Not having the "foreach"-style for
loop leads to many off-by-one errors, and makes a lot of simple code much more verbose.
Not having the C-style for
loop makes some already-very-complicated for
loops slightly more complicated by forcing them to be while
loops. It doesn't affect simple loops like yours, which can be written as "foreach" loops, like for i in range(10):
—which is briefer, and more readable, and harder to get wrong.*
When looked at that way, the choice is obvious.
* In fact, even complex loops can be turned into foreach loops, via iterators. And sometimes that's a good idea. For example, is for (int i=2; i=next_prime(i); i<1000000)
really better than for i in takewhile(lambda i: i<1000000, generate_primes()):
? There's a reason that C++ has gradually added features to make the latter possible, to avoid the mistakes you can easily make with the former…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With