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):
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.
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“.
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.
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.range creates a list, so if you do
range(1, 10000000)
it creates a list in memory with9999999
elements.
xrange
is a generator, so itis a sequence objectis athat 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With