why no "do : until"?

Tim Peters tim.one at home.com
Thu Jan 4 21:05:43 EST 2001


[Bjorn Pettersen]
> ...
> (perhaps "for i in 1..10" or perhaps a special form of
> list comprehensions "for i in [1..10 by 2]" <wink>)

[Alex Martelli]
> Surely, if a special syntax existed for what's now written as
> "range(1,10)", it would be absurd to restrict it to being used
> in for loops -- why add rules (complication) to _diminish_
> expressiveness?  I know that a PEP on such a proposal was reently
> rejected, but I don't know why.

Part of the PEP process is writing a patch to implement the idea.  I was the
reviewer for the patch (which was very well done -- no problem there), and
after trying the [i:j:k] notation in practice for a few hours, I liked it
less the more I used it.  For example, it was too easy to forget the square
brackets; and, e.g.,

    for i in [0:len(a)]:

was really no improvement at all (I came to think of it as worse) over

    for i in range(len(a)):

One specific problem is that slice notation for *indexing* has context, by
which I mean that

    a[1:]   # all but the first element of a

can omit the endpoint because it's conveniently supplied by "a".  But the
standalone [i:j:k] notation doesn't have any context to exploit, so it was
just as wordy as calling range.  Also didn't help that as code grew denser,
my eye couldn't immediately distinguish uses of "[]" for indexing from uses
for range-building.  For that reason I believe a notation like 1..10 would
be better -- provided it's needed at all.

Anyway, that lead to a discussion, and it turned out nobody liked the
[i:j:k] notation enough to fight for it.  The patch author wrote that even
he didn't like it, but wrote the patch because Guido told him he should
<wink>.

I count this as a clear success for the PEP process!  [i:j:k] may well have
gotten into the language otherwise (e.g., I was initially favorable, and
more importantly so was Guido).

My own years-old suggestion for a "for" enhancement is the "indexing"
proposal, an optional clause on "for":

    for i indexing a:
    for i indexing x in a:

A study I did at the time said that about 15% of all "for" loops in Python
code were of the form

    for i in range(len(a)):

and that's both an obscure and inefficient way to spell the underlying idea.
As an implementer, it also repels me <0.6 wink>:  Python *always* constructs
an integer index under the covers, and what "for i in range(len(a))" really
does is build a list of the integers 0, 1, 2, ..., len(a)-1; then the for
loop mechanism generates the same integers one at a time all by itself; and
then it passes each in turn to list.__getitem__(), all in order to get back
the same integers it passes!  One of the Missing Pythonic Theses is "where
the implementation is absurd, Guido was too Spartan" <wink>.

it's-enough-that-"while-1"-keeps-testing-the-truth-of-"1"-ly y'rs
    - tim





More information about the Python-list mailing list