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.
| Feature | range (Python 2) | xrange (Python 2) |
|---|---|---|
| Return Type | Returns a list of numbers. | Returns an iterator (or generator-like object). |
| Memory Usage | Uses more memory (stores all numbers in memory). | Uses less memory (generates numbers on demand). |
| Speed | Slower for large ranges (due to list creation). | Faster and more memory-efficient. |
| Iteration | Can be iterated multiple times. | Can be iterated only once (like a generator). |
| Availability | Works 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 listOutput (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 likexrange()(lazy evaluation, efficient).
- Only
