1
Jul

Difference between range() and xrange()

Question:

Write a program to show the difference between range() and xrange() function

Program:

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: