why I don't like range/xrange

stdazi stdazi at gmail.com
Fri Feb 16 10:30:15 EST 2007


Hello!

Many times I was suggested to use xrange and range instead of the
while constructs, and indeed, they are quite more elegant - but, after
calculating the overhead (and losen flexibility) when working with
range/xrange, and while loops, you get to the conclusion that it isn't
really worth using range/xrange loops.

I'd like to show some examples and I'll be glad if someone can suggest
some other fixes than while a loop :-)

a) range overfllow :


for i in range(0, 1 << len(S)) :
.....
OverflowError: range() result has too many items

ok, so we fix this one with xrange !

b) xrange long int overflow :

for i in xrange(0, 1 << len(S)) :
........
OverflowError: long int too large to convert to int

Next thing I miss is the flexibility as in C for loops :

for (i = 0; some_function() /* or other condition */ ; i++)

or,

for (i = 0 ; i < 10 ; i++)
   i = 10;


I don't think range/xrange sucks, but I really think there should be
some other constructs to improve the looping flexibility. Other thing
may be, that I just miss an equally elegant alternative that's why I'd
like to hear some suggestions on how to fix the above issues.. (btw,
I've already browsed the archives related to my issue,but i don't see
any good solution)

Thanks

Jernej.




More information about the Python-list mailing list