why I don't like range/xrange

Paul McGuire ptmcg at austin.rr.com
Fri Feb 16 11:09:09 EST 2007


On Feb 16, 9:30 am, "stdazi" <std... at gmail.com> wrote:
> 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.

Very little of my own code uses range or xrange, most of my for loops
iterate over a sequence or generator, as in "for item in blahList: do
something with item".   I think range/xrange are common beginner's
constructs, since they reflect a more C-like looping method ("for i in
range(len(blahList)): do something with blahList[i]").

I really would *not* encourage use of range/xrange, but feel that
iteration over sequences and generators is the more elegant/Pythonic
way to go - who is suggesting you use range/xrange?

For that matter, just what is it you plan to do 2**len(S) times?  If S
is of any significant length, the sun may be a lump of coal before you
are finished, regardless of what loop mechanism you use (although it
would make sense to avoid range's implementation of creating a list of
2**len(S) items - fortunately the implementation already resolves this
problem by raising a "that's too many items" exception, and thankfully
so).

Maybe instead of working around range/xrange, you should think whether
a 2**len(S) approach to your problem is feasible in the first place.

-- Paul




More information about the Python-list mailing list