In Python 2, range()
and xrange()
were both used to generate sequences of numbers, but they worked differently:
range()
:- In Python 2,
range()
returned a list of numbers. For example,range(5)
would return[0, 1, 2, 3, 4]
. - It generated the entire list in memory, which could be inefficient if the range is large.
- In Python 2,
xrange()
:xrange()
in Python 2 returned an iterator, not a list. This means it didn’t generate the entire sequence at once, but instead generated each number in the sequence on demand (lazily).- This made
xrange()
more memory-efficient for large ranges.
In Python 3:
xrange()
was removed and therange()
function was changed to behave likexrange()
did in Python 2.- So, in Python 3,
range()
is now an iterator and is much more memory-efficient compared to the Python 2range()
, because it doesn’t generate a full list in memory.
Key differences:
- Python 2:
range()
→ returns a listxrange()
→ returns an iterator
- Python 3:
range()
→ behaves likexrange()
from Python 2 (returns an iterator)
In short: If you’re using Python 3, just use range()
. If you’re on Python 2, use xrange()
when you want better memory efficiency.