[Python-Dev] Lockstep iteration - eureka! (original) (raw)

Tim Peters tim_one@email.msn.com
Wed, 16 Aug 2000 01:12:21 -0400


[Paul Prescod]

... I really don't see this "indexing" issue to be common enough

A simple grep (well, findstr under Windows) finds over 300 instances of

for ... in range(len(...

in the .py files on my laptop. I don't recall exactly what the percentages were when I looked over a very large base of Python code several years ago, but I believe it was about 1 in 7 for loops.

for special syntax OR to worry alot about efficiency.

1 in 7 is plenty. range(len(seq)) is a puzzler to newbies, too -- it's such an indirect way of saying what they say directly in other languages.

Nobody is forcing anyone to use .items().

Agreed, but since seq.items() doesn't exist now .

If you want a more efficient way to do it, it's available (just not as syntactically beautiful -- same as range/xrangel).

Which way would that be? I don't know of one, "efficient" either in the sense of runtime speed or of directness of expression. xrange is at least a storage-efficient way, and isn't it grand that we index the xrange object with the very integer we're (usually) trying to get it to return ? The "loop index" isn't an accident of the way Python happens to implement "for" today, it's the very basis of Python's thing.getitem(i)/IndexError iteration protocol. Exposing it is natural, because it is natural.

... Also, if .keys() returns a range object then theoretically the interpreter could recognize that it is looping over a range and optimize it at runtime.

Sorry, but seq.keys() just makes me squirm. It's a little step down the Lispish path of making everything look the same. I don't want to see float.write() either .

although-that-would-surely-be-more-orthogonal-ly y'rs - tim