why I don't like range/xrange

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Feb 16 16:44:01 EST 2007


stdazi a écrit :
> 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've almost never had to use (x)range in a for loop. Usually, one just 
iterate over an iterable.

(snip)


> Next thing I miss is the flexibility as in C for loops :
> 
> for (i = 0; some_function() /* or other condition */ ; i++)

You may want to have a look at generators. The main idea here is to 
encapsulate the knowledge about how iteration is implemented, so the 
client code just have to iterate.

> or,
> 
> for (i = 0 ; i < 10 ; i++)
>    i = 10;

for i in range(10):
   i = 10

What's your point, exactly ?

> 
> I don't think range/xrange sucks, but I really think there should be
> some other constructs to improve the looping flexibility. 

Have a look at generators then.



More information about the Python-list mailing list