Long integers and ways around xrange

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Jan 16 21:25:44 CET 2010

On Sat, 16 Jan 2010 20:04:09 +0100, Martin Manns wrote:

> Hi
> As stated in the manual, xrange raises an OverflowError for long integer
> parameters. Looking for a xrange like generator for long integers, I
> found this in the manual
> (http://docs.python.org/library/functions.html):
>> CPython implementation detail: xrange() is intended to be simple and
>> fast. Implementations may impose restrictions to achieve this. The C
>> implementation of Python restricts all arguments to native C longs
>> (“short” Python integers), and also requires that the number of
>> elements fit in a native C long. If a larger range is needed, an
>> alternate version can be crafted using the itertools module:
>> islice(count(start, step), (stop-start+step-1)//step).
> However, count only accepts one parameter, so that this solution does
> not work. Furthermore, islice only accepts positive values for step.

This should be reported as a documentation bug.

> I came up with a solution that I have pasted below.
> Is there a standard long integer replacement for xrange? 

Not really. There are many ways of implementing it, and it really depends 
on what you care most about: speed, memory consumption, simplicity, 
economy of code, or something else. Chances are that only memory 
consumption is critical for any real application.

This is probably the simplest you can get:

def myxrange(start, end, step):
    n = start
    while n < end:
        yield n
        n += step

Adding error checking, useful defaults, and support for negative step 
values is left as a exercise *wink*

> Do you have ideas for improving the code?

Only quibbles.

E.g. you set the module encoding to utf-8, but don't use any non-ASCII 

In the lambda in scount, you use x for an argument which is an int not a 
float. I would use i rather than x to make that clear.

As I said, quibbles.


More information about the Python-list mailing list