reversed() vs. xrange()

768 Views Asked by At

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

2

There are 2 best solutions below

3
On BEST ANSWER

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.

2
On

xrange() produces a sequence of numbers. You can then use those numbers as list indices if you want, or you can use them for anything where you want those numbers.

for i in xrange( len(l)-1, -1, -1):
    item = l[i]
    print item

reversed() produces the items from something that has a length and can be indexed.

for item in reversed(l):
    print item

I would use reversed() because it makes you code shorter, simpler, clearer, and easier to write correctly.