The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Secret Catacombs

--

Chapters
00:00 What Is The Difference Between Range And Xrange Functions In Python 2.X?
00:22 Answer 1 Score 44
00:34 Accepted Answer Score 1042
01:06 Answer 3 Score 240
01:35 Answer 4 Score 70
02:01 Thank you

--

Full question
https://stackoverflow.com/questions/9493...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #loops #range #python2x #xrange

#avk47



ACCEPTED ANSWER

Score 1042


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.



ANSWER 2

Score 240


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))



ANSWER 3

Score 70


xrange only stores the range params and generates the numbers on demand. However the C implementation of Python currently restricts its args to C longs:

xrange(2**32-1, 2**32+1)  # When long is 32 bits, OverflowError: Python int too large to convert to C long
range(2**32-1, 2**32+1)   # OK --> [4294967295L, 4294967296L]

Note that in Python 3.0 there is only range and it behaves like the 2.x xrange but without the limitations on minimum and maximum end points.




ANSWER 4

Score 44


xrange returns an iterator and only keeps one number in memory at a time. range keeps the entire list of numbers in memory.