Python · Memory & Internals

range() in Python 2 vs Python 3

Hardrangexrangepython2python3lazy

Interview question

How does range() differ between Python 2 and Python 3?

How to answer

The short answer

In Python 2:

  • range(n) eagerly built a list of integers (memory heavy for large n).
  • xrange(n) returned an xrange object that generated values lazily.

In Python 3:

  • range(n) returns a lazy range object (immutable sequence) that computes values on demand.
  • There is no xrange; Py3 range covers that role.
  • You can index, slice, and take len(), but it is not a list. Use list(range(...)) if you need a real list.
Python
# Python 3
r = range(1_000_000)
print(type(r))      # <class 'range'>
print(len(r))       # 1000000
print(r[10])        # 10
print(r[:3])        # range(0, 3)
print(list(r[:3]))  # [0, 1, 2]

# Memory: range object is tiny vs equivalent list
import sys
print(sys.getsizeof(range(1_000_000)))
print(sys.getsizeof(list(range(1_000))))  # already much larger for smaller n

Migration note: Code that depended on range returning a list in Py2 must wrap with list(...) under Py3 if mutation/list methods are required.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill