Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Large number in Python

Tags:

python

We have number "17179869184" which need to traverse. But we got memory error when we traverse into list. is there anyway we can handle similar kind of range number

for i in range(17179869184):
    print i

for i in xrange(17179869184):
    print i



Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    for i in xrange(17179869184):
OverflowError: Python int too large to convert to C long
like image 689
user765443 Avatar asked Aug 23 '26 17:08

user765443


2 Answers

You can use itertools.count with iter:

>>> from itertools import count
>>> c = count(0)
>>> for i in iter(c.next, 17179869184):
        #do something with i

Note that if you only want to loop that number of times, i.e you're not using i inside the loop then it will be better to use itertools.repeat:

>>> from itertools import repeat
>>> for _ in repeat(None, 17179869184):
...     # do something here
like image 71
Ashwini Chaudhary Avatar answered Aug 25 '26 08:08

Ashwini Chaudhary


Use a while loop:

i=0
while i < 17179869184:
    # do stuff
    i += 1

If this is being done multiple times, create a Python implementation of range() using generators.

def py_range(num):
    i = 0
    while i < num:
        yield i
        i+=1

Well, py_range() not the same as range() as it has start and other arguments. But you can search online for a complete implementation (should be there).

like image 33
Ramchandra Apte Avatar answered Aug 25 '26 07:08

Ramchandra Apte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!