while (a=b()) ...

Tim Peters tim_one at email.msn.com
Sun May 16 21:42:48 EDT 1999


[Tim]
> "for x in thing:" follows a protocol that's *defined* to call
> thing.__getitem__ first with 0, then with 1, and so on.

[Hrvoje Niksic]
> ...and at that, it's a very ugly protocol.  If memory serves me right,
> you're supposed to signal end-of-sequence by explicitly raising
> IndexError.

Heck of a lot better than leaving the loop as soon as the object returns,
say, 42.

> I wonder how expensive it is to trap and raise exceptions
> in Python (I haven't looked at the interpreter code).

"try" is cheap; a non-triggered "except" is free; a triggered "except" is
relatively expensive; sequence iteration triggers an exception once per
loop.

> Maybe that's why xrange() is slower than range() when common sense
> says it should be the other way around.

You need to be much clearer about your claim here; certainly xrange(1000000)
runs much faster than range(1000000) on anyone's machine (the former is
constant time regardless of argument and the latter at best takes time
proportional to a million), so your real complaint is about something else.
If you mean that

    for i in xrange(N): pass

is slower than

    for i in range(N): pass

that could be, but the xrange version is still substantially (~30%) faster
on my machine for N=10000.  The relative speed is very platform dependent,
alas.  *All* "for" loops (whether spelled with range, xrange, "in", or
myClassInstance) terminate by raising IndexError, though, so it's a wash in
that respect.

> ...
> I don't speak for Jim, but the asterisk is horribly unintuitive to me.
> Almost reminiscent of that other language.

Hrvoje, you're a veritable master of understatement today <wink>!

forestalling-the-asterisk-tragedy-ly y'rs  - tim






More information about the Python-list mailing list