What is the difference between "range" and "xrange" in Python 2?

In Python 2, there is a difference between the range and xrange functions, which relates to their behavior in terms of memory usage and performance:


  • The range function returns a list of numbers as a sequence. It generates and stores all the numbers in memory before returning the list.
  • When you call range with a large range of numbers, it generates the entire list at once, which can consume significant memory, especially for large ranges.


  • The xrange function returns an iterable object that generates the numbers on the fly as they are needed. It does not generate the entire list in memory.
  • xrange is a generator function, and it generates the numbers lazily or on-demand, one at a time. This approach is more memory-efficient because it generates numbers as they are needed, rather than pre-allocating memory for the entire sequence.
  • The advantage of using xrange is that it can be more efficient when dealing with large ranges, as it avoids unnecessary memory usage.

Here's an example to demonstrate the difference between range and xrange in Python 2:

# Example using range
numbers_range = range(10**6)  # Creates a list of one million numbers
print(sum(numbers_range))  # Consumes memory for the entire list

# Example using xrange
numbers_xrange = xrange(10**6)  # Creates an iterable object
print(sum(numbers_xrange))  # Generates numbers on-demand, conserving memory

In this example, when using range, the range(10**6) call generates a list of one million numbers in memory. The entire list is stored in memory, consuming significant memory resources.

On the other hand, when using xrange, the xrange(10**6) call creates an iterable object that generates the numbers on-demand. The numbers are not generated and stored in memory all at once, but rather generated one at a time as needed, conserving memory.

It's important to note that in Python 3, the range function behaves similarly to the xrange function in Python 2. Python 3's range function returns a lazy iterable object rather than a list, providing memory-efficient behavior by default.

In Python 2, if you need to iterate over a large range and want to conserve memory, it is recommended to use xrange instead of range. However, in Python 3, you can simply use the range function, which behaves like xrange in Python 2.

Related Questions You Might Be Interested