The Difference Between xrange and range in Python
http://www.quora.com/What-is-the-difference-between-range-and-xrange-how-has-this-changed-over-time
In python 2.x range() returns a list and xrange() returns an xrange object, which is kind of like an iterator and generates the numbers on demand.(Lazy Evaluation)
In python 3.x xrange() has been removed and range() now works likexrange() and returns a range object.
xrange returns a xrange object which is of fixed length and yet behaves in the same way allowing iteration. Thus, it might have some performance advantages with respect to memory.
xrange is generator, much more efficient if the number is large, generate x on demand
http://www.quora.com/What-is-the-difference-between-range-and-xrange-how-has-this-changed-over-time
In python 2.x range() returns a list and xrange() returns an xrange object, which is kind of like an iterator and generates the numbers on demand.(Lazy Evaluation)
In python 3.x xrange() has been removed and range() now works likexrange() and returns a range object.
xrange returns a xrange object which is of fixed length and yet behaves in the same way allowing iteration. Thus, it might have some performance advantages with respect to memory.
xrange is generator, much more efficient if the number is large, generate x on demand
The only difference is that range returns a Python list object and xrange returns an xrange object.
What does that mean? Good question! It means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding.
Deprecation of Python's xrange
One more thing to add. In Python 3.x, the xrange function does not exist anymore. The range function now does what xrange does in Python 2.x, so to keep your code portable, you might want to stick to using range instead.
Should you always favor xrange() over range()?
- In python 3,
range()
does whatxrange()
used to do andxrange()
does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't usexrange()
. range()
can actually be faster in some cases - eg. if iterating over the same sequence multiple times.xrange()
has to reconstruct the integer object every time, butrange()
will have real integer objects. (It will always perform worse in terms of memory however)xrange()
isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.