In Python 2.x:
range
creates a list, so if you dorange(1, 10000000)
it creates a list in memory with9999999
elements.xrange
is a generator object that evaluates lazily.
In Python 3, range
does the equivalent of python’s xrange
, and to get the list, you have to use list(range(...))
.
xrange
brings you two advantages:
- You can iterate longer lists without getting a MemoryError.
- As it resolves each number lazily, if you stop iteration early, you won’t waste time creating the whole list