What is the difference between range and xrange functions in Python 2.X?
Solution 1:
In Python 2.x:
-
range
creates a list, so if you dorange(1, 10000000)
it creates a list in memory with9999999
elements. -
xrange
is a sequence object that evaluates lazily.
In Python 3:
-
range
does the equivalent of Python 2'sxrange
. To get the list, you have to explicitly uselist(range(...))
. -
xrange
no longer exists.
Solution 2:
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))