The difference between range and xrange mainly applies to Python 2.
In Python 3, the xrange() function was removed, and range() now behaves like xrange() used to.

Both are used to generate a sequence of numbers, but they differ in memory usage and performance.


Featurerange (Python 2)xrange (Python 2)
Return TypeReturns a list of numbers.Returns an iterator (or generator-like object).
Memory UsageUses more memory (stores all numbers in memory).Uses less memory (generates numbers on demand).
SpeedSlower for large ranges (due to list creation).Faster and more memory-efficient.
IterationCan be iterated multiple times.Can be iterated only once (like a generator).
AvailabilityWorks in both Python 2 and 3.Only available in Python 2. Removed in Python 3.

🧩 Example 1: Using range in Python 2

# Python 2 example
nums = range(5)
print(nums)

Output (Python 2):

[0, 1, 2, 3, 4]

🧩 Example 2: Using xrange in Python 2

# Python 2 example
nums = xrange(5)
print(nums)

Output (Python 2):

xrange(0, 5)

(It returns an xrange object, not a list.)

To see the numbers:

for i in xrange(5):
    print(i)

Output:

0
1
2
3
4

🧩 Example 3: Modern Python 3 Equivalent
In Python 3, there is no xrange(), and range() behaves like xrange() did in Python 2.

nums = range(5)
print(nums)           # Returns a range object
print(list(nums))     # Converts it to a list

Output (Python 3):

range(0, 5)
[0, 1, 2, 3, 4]

In Summary:

  • In Python 2,
    • range() → returns a list (uses more memory).
    • xrange() → returns an iterator (memory efficient).
  • In Python 3,
    • Only range() exists, and it behaves like xrange() (lazy evaluation, efficient).

Scroll to Top