Python for loop range (bigint)

There is some short way in Python to do something like

"for i in range (n)"

when is n too large for Python to actually create an array range (n)?

(short, because otherwise I would just use a while loop)

+3
source share
4 answers

You can use xrange () ... although this is limited to "short" integers in CPython:

CPython: xrange() . . Python C longs ( "" Python), , C . , itertools: takewhile(lambda x: x<stop, (start+i*step for i in count())).

, ( ), ...

, bigint , , , - , , xrange , , range.

+5

: .

def gen():
    i = 0
    while 1: # or your special terminating logic
        yield i
        i = i + 1


for j in gen():
    do stuff
+3

You can upgrade to python3. There, the range is not limited to β€œshort” integers.

Another workaround would be to use xrange for small integers and add them to some constant inside the loop, for example.

offset, upperlimit = 2**65, 2**65+100
for i in xrange(upperlimit-offset):
    j = i + offset
    # ... do something with j
+1
source

you should always use xrange, not the range, in order to just loop n times more than sth., but keep in mind that xrange also has a limit (if it's too small, you need to make your own while loop with a counter)

EDIT: too late ...

0
source

Source: https://habr.com/ru/post/1752581/


All Articles