SoFunction
Updated on 2025-04-23

Difference between range and xrange in python (python2 and python3)

In Python,range()andxrange()Functions played different roles in earlier Python versions (Python 2), but in Python 3,xrange()Have been removed andrange()Replace. The following explains the differences between these two functions in Python 2 and the changes in Python 3 respectively.

The difference in Python 2

range(): This function generates a list in Python 2, containing a sequence of integers from the specified start value to the end value (excluding the end value). This list is created in memory immediately, so if the generated sequence of numbers is large, it will consume a lot of memory.

# Python 2  
for i in range(10):  
    print(i)  
# This creates an instantly containing0arrive9List of

xrange(): This function generates an iterator-like object in Python 2 to generate a sequence of numbers, but it does not create the entire list in memory immediately. It is designed to save memory, especially when processing large amounts of data.xrange()The generated sequence will only produce values ​​when it is iterated.

# Python 2  
for i in xrange(10):  
    print(i)  
# This will not create a list immediately,Instead, generate numbers on demand

Changes in Python 3

In Python 3,range()The behavior of the function is similar to that in Python 2xrange(), i.e. it returns an iterable object, not a list. This means that in Python 3range()It is more memory-saving in functionality, as it does not require loading all values ​​into memory at once.

# Python 3  
for i in range(10):  
    print(i)  
# This isPython 3Similar toPython 2In-housexrange(),All generate numbers on demand

So, in Python 3,xrange()No longer exists,range()Already integratedxrange()Advantages of  . If you are migrating from Python 2 to Python 3 and your code usesxrange(), you can simply replace them withrange(), without worrying about memory usage or behavior changes.

This is the end of this article about the difference between range and xrange in python (python2 and python3). For more related python range xrange content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!