Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there no control structures for python FOR loop?

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?

like image 943
George Newton Avatar asked Dec 15 '22 04:12

George Newton


2 Answers

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.

like image 74
rob mayoff Avatar answered Dec 31 '22 06:12

rob mayoff


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…

like image 41
abarnert Avatar answered Dec 31 '22 05:12

abarnert