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?

2
  • 1
    In Python 3, range() creates an iterator, but in Python 2 range() creates a list. In Python 2, use xrange() instead to create an iterator. Commented Aug 20, 2017 at 17:56
  • Try using xrange() Commented Aug 20, 2017 at 17:56

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.