I tried it on here but it can not print the long numbers like this
for i in range(1,222222222222222):
print i
Error:
Traceback (most recent call last):
File "x.py", line 1, in <module>
for i in range(1,222222222222222):
MemoryError
I tried it on here but it can not print the long numbers like this
for i in range(1,222222222222222):
print i
Error:
Traceback (most recent call last):
File "x.py", line 1, in <module>
for i in range(1,222222222222222):
MemoryError
Use xrange
.
for i in xrange(1, 222222222222222):
print i
This function is very similar to range(), but returns an “xrange object” instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously.
You are probably using Python2, where range()
produces a list of numbers. A list with 222222222222222 elements is quite large, too large for most RAMs.
In contrast to this, xrange()
produces an xrange object which can be accessed like a list (indexed, iterated), but doesn't occupy as much space because the values are computed on-demand.
In Python3, range()
returns a range object which is quite the same as the xrange object in 2.x.
Use xrange instead of range. range generates a list, stores it in the memory and performs the loop on each item. This generates memory errors when dealing with quite big numbers.
xrange is a generator not a list, items are created on the fly, so it does not harm for the memory
I hope this helps
Use xrange instead. The range function actually constructs the list in memory, while xrange returns a generator (similar to an iterator), and returns only one number at a time.
for i in xrange(1,222222222222222L):
print i
See more on the topic here
Python creates the range before you start the loop, resulting in a huge amount of memory use/oom error.
you're better off using xrange, it allocates the range in smaller pieces.
for i in xrange(from, to):
print i
you can also create generator using yield on your own:
def my_gen(start, end, step):
while start < end:
start += step
yield start
for x in my_gen(1, 1000, 2):
print x
Check this example of While Loop
a = 0
while a < 10 :
a += 1
print (a)
You can also do the same using "For Loop"
onetoten = range(1,11)
for count in onetoten:
print (count)