0

Testing with Python 2.7 and 3.5

for i in range(0, 1000000000):
    pass

When I'm running this code with python3 everything is fine (less than 3MB memory usage)

But by python2 memory usage is 32GB (my server has only 32GB of ram)

How to fix this for Python 2.7?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
John Kotkin
  • 191
  • 1
  • 7

1 Answers1

3

range in Python 2.7 and range in Python 3 are different functions. In Python 3 it returns an iterator which provides values one by one. In Python 2.7 it returns an array for which some memory has to be allocated. It can be solved by using xrange function in Python version 2.7.

Python 2.7.12
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> xrange(10)
xrange(10)
>>> iterator = iter(xrange(10))
>>> iterator.next()
0
>>> iterator.next()
1
>>> iterator.next()
2
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79