Question:
Write a program to show the difference between range() and xrange() function
Program:
1 2 3 4 5 6 7 |
import sys r=range(10000) x=xrange(10000) print (sys.getsizeof(r)) #output:40036 print (sys.getsizeof(x)) #output:20 #sys.getsizeof() returns the memory size occupied by a variable or object |
Explanation:
The variable holding the range created using range() uses so much memory compared to
the variable created using xrange()
The reason is that range creates a list holding all the values
while xrange creates an object that can iterate over the numbers on demand.
Eventhough the xrange is memory efficient, the price we have to pay
for this efficieny is access time. The range variable created with range()
will have a faster access time compare to the variable created with xrange()
as it is entirely stored in the memory so it is readily available
whereas the variable created with xrange() have to load its contents
to memory ‘on demand’ only. So time efficiency is a drawback of xrange()
Output:
1 2 |
80072 40 |
Leave a Reply