Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between range and xrange functions in Python 2.X?

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): 
like image 586
Teifion Avatar asked Sep 18 '08 17:09

Teifion


People also ask

What's the difference between range and Xrange?

For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and xrange returns an xrange object.

What is the difference between Xrange and range in a Python loop?

The areas of difference for xrange and range are : Return Type: Range returns a list but xrange returns an xrange object. Memory: Range utilizes more memory than xrange as range creates the whole list at once but xrange creates the value required at execution and is also known as “lazy evaluation“.

What is Xrange () Python?

The xrange() function in Python is used to generate a sequence of numbers, similar to the range() function. However, xrange() is used only in Python 2. x whereas range() is used in Python 3.


2 Answers

In Python 2.x:

  • range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.

  • xrange is a sequence object that evaluates lazily.

In Python 3:

  • range does the equivalent of Python 2's xrange. To get the list, you have to explicitly use list(range(...)).
  • xrange no longer exists.
like image 57
Charles Avatar answered Sep 17 '22 16:09

Charles


range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.

xrange is a generator, so it is a sequence object is a that evaluates lazily.

This is true, but in Python 3, range() will be implemented by the Python 2 xrange(). If you need to actually generate the list, you will need to do:

list(range(1,100)) 
like image 43
Corey Avatar answered Sep 20 '22 16:09

Corey