Search code examples
pythonlisttraversalxrange

reversed() vs. xrange()


I need to traverse a list backwards. I read about xrange() and reversed(). Which one is more expensive?


Solution

  • You can use Python's timeit library to time things like this. You don't say what kind of list you have, so I am assuming a simple list of strings. First I create a list 100 items long and then time both:

    my_list = ["hello"] * 100
    
    def v1():
        for x in my_list[::-1]:
            pass
    
    def v2():
        for x in reversed(my_list):
            pass
    
    print timeit.timeit(v1)
    print timeit.timeit(v2)
    

    This gives the following result:

    2.78170533583
    2.13084949985
    

    As you can see, in this example reversed() is a bit faster.