rangepython-2.xxrange

Should you always favor xrange() over range()?


Why or why not?


Solution

  • 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 range():

    [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 range() and xrange()

    RefactoringTool: Skipping implicit fixer: buffer
    RefactoringTool: Skipping implicit fixer: idioms
    RefactoringTool: Skipping implicit fixer: ws_comma
    --- range_test.py (original)
    +++ range_test.py (refactored)
    @@ -1,7 +1,7 @@
    
     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.