range() vs xrange() in Python, Which one is best ? with example
In this tutorial, you will know about range() vs xrange() in python.
First understand basic definition of range() and xrange().
range() function:
This is inbuilt function in python library. This function create lists with sequence of values. It’s mostly used in for loops. You have pass integer as arguments . This function comes with start and stop numbers. you can specify range that you want. If you want range with some steps you can use step argument.
Syntax : range(start, stop[, step])
for i in range(10):
print(i)
for i in range(1,10):
print(i)
for i in range(1,10,2):
print(i)
xrange() function:
xrange() similar like range function but it doesn’t have slicing. it will return xrange object. it will be used to save memory when a very large range is used on a memory-starved machine.
Syntax: xrange(start, stop[, step])
Compute Time for Range() and Xrange() functions
Note: xrange is not available in Python3. You have to use range() function to run on both versions. Here i am using python 3.x version, you will get error for xrange() function. if you want to know about xrange() function try it python 2.x version.
import time
start = time.time()
#initializing 10000 random numbers using range() function
a = range(1,10000)
end = time.time()
print(end - start)
import time
start = time.time()
#initializing 10000 random numbers using xrange() function
b = xrange(1,10000)
end = time.time()
print(end - start)
Compute Space for Range() and Xrange() functions
Note: xrange is not available in Python3. You have to use range() function to run on both versions.
import sys
#initializing 10 random numbers using range() function
a = range(1,10)
print ("Memory size for a",sys.getsizeof(a))
#initializing 10 random numbers using range() function
b = xrange(1,10)
print ("Memory size for b",sys.getsizeof(a))