What is the difference between range and xrange functions in Python 2.X?

Technology CommunityCategory: PythonWhat is the difference between range and xrange functions in Python 2.X?
VietMX Staff asked 3 years ago

In Python 2.x:

  • range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 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