What is the difference between range() and xrange() in Python?
Why Interviewers Ask This
This is a classic screening question for Python roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.
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).
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last Python project, I used this when...' immediately makes your answer more credible and memorable.