🐍 Python
Beginner
What is the difference between range() and xrange() in Python?
Answer
This question is specific to Python 2 vs Python 3. In Python 2, range() returned a full list of numbers in memory, while xrange() returned a lazy iterator that generated numbers on demand — much more memory-efficient for large ranges. In Python 3, xrange() was removed, and range() was reimplemented to behave like Python 2's xrange() — it returns a lazy range object that generates numbers on demand without storing them all in memory. So range(1000000) in Python 3 uses only a few bytes regardless of size, whereas in Python 2, range(1000000) would create a list of one million integers. You can still slice a range: range(10)[2:5] returns range(2, 5).