Should you always favor xrange() over range()?
For performance, especially when you're iterating over a large range,
xrange() is usually better. However, there are still a few cases why you might prefer
In python 3,
xrange()used to do and
xrange()does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use
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, but
range()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.
[Edit] There are a couple of posts mentioning how
range() will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of
RefactoringTool: Skipping implicit fixer: bufferRefactoringTool: Skipping implicit fixer: idiomsRefactoringTool: Skipping implicit fixer: ws_comma--- range_test.py (original)+++ range_test.py (refactored)for x in range(20):- a=range(20)+ a=list(range(20)) b=list(range(20)) c=[x for x in range(20)] d=(x for x in range(20))- e=xrange(20)+ e=range(20)
As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.
No, they both have their uses:
xrange() when iterating, as it saves memory. Say:
for x in xrange(1, one_zillion):
for x in range(1, one_zillion):
On the other hand, use
range() if you actually want a list of numbers.
multiples_of_seven = range(7,100,7)print "Multiples of seven < 100: ", multiples_of_seven
You should favour
xrange() only when you need an actual list. For instance, when you want to modify the list returned by
range(), or when you wish to slice it. For iteration or even just normal indexing,
xrange() will work fine (and usually much more efficiently). There is a point where
range() is a bit faster than
xrange() for very small lists, but depending on your hardware and various other details, the break-even can be at a result of length 1 or 2; not something to worry about. Prefer