Xrange versus itertools.count Python 2.7
I want to run a range from start to end value. It works fine at low numbers, but when it gets too large, it throws an overflow error as too big to convert to C Long. I am using Python 2.7.3.
I read here OverflowError Python int is too big to convert to C long using a method itertools.count()
, except that this method works differently with a stepped method xrange
as opposed to declaring a finite range value.
Can it be configured itertools.count()
to work like xrange()
?
print "Range start value"
start_value = raw_input('> ')
start_value = int(start_value)
print "Range end value"
end_value = raw_input('> ')
end_value = int(end_value)
for i in xrange(start_value, end_value):
print hex(i)
source to share
You can use itertools.islice()
to give an count
end:
from itertools import count, islice
for i in islice(count(start_value), end_value - start_value):
islice()
calls StopIteration
after the values end_value - start_value
have been iterated over.
Support for a step size other than 1 and combining it into a function would be as follows:
from itertools import count, islice
def irange(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
length = 0
if step > 0 and start < stop:
length = 1 + (stop - 1 - start) // step
elif step < 0 and start > stop:
length = 1 + (start - 1 - stop) // -step
return islice(count(start, step), length)
then use irange()
as you would use range()
or xrange()
, except you can now use Python integers long
:
>>> import sys
>>> for i in irange(sys.maxint, sys.maxint + 10, 3):
... print i
...
9223372036854775807
9223372036854775810
9223372036854775813
9223372036854775816
source to share