0 votes
1 view
in Python by (47.8k points)

Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

for i in range(0, 20):

for i in xrange(0, 20):

1 Answer

0 votes
by (107k points)
edited by
  • range() and xrange() are two functions that can be used to iterate a certain number of times in a for loop in Python. xrange()is only used in, Python 2. So to run any code in both Python 2 and Python 3 you should use range() function.

  • range() – It will create a list of values from depending on the range specified

  • xrange() – It returns xrange objects that can be used to display numbers only by looping. The only a particular range is displayed on demand and hence called “lazy evaluation“.

  • Now the point is why xrange() is faster as compared to range(). The reason is, at the time of the memory allocation range() takes more amount of memory as compares to xrange (). The basic reason for this is the return type of range() is a list which is large in size and the return type of xrange() is xrange() object which needs less amount of memory.

  • An example that illustrates all the above points:-

import sys

a = range(1,10000)

x = xrange(1,10000)

print ("The size allotted using range() is:")

print (sys.getsizeof(a))

print ("The size allotted using xrange() is : ")

print (sys.getsizeof(x))

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...