In Python, is there some short way to do something like
"for i in range(n)"
when n is too big for Python to actually create the array range(n)?
(short because otherwise I'd just use a while loop)
You could use xrange()... although that is restricted to "short" integers in CPython:
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:
takewhile(lambda x: x<stop, (start+i*step for i in count())).
I don't know whether that restriction also applies to other implementations (or which ones) - but there's a workaround listed...
I know you mention bigint in your question title, but the question body talks about the number being too big to create the array - I suspect there are plenty of numbers which are small enough for xrange to work, but big enough to cause you memory headaches with range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With