20
votes

What is typically regarded as more Pythonic/better/faster to use, the reverse method or the reversed built-in function?

Both in action:

_list = list(xrange(4))

print _list

rlist = list(reversed(_list))

print rlist

_list.reverse()

print _list
6

6 Answers

12
votes

Depends on whether you want to reverse the list in-place (i.e. change the list) or not. No other real difference.

Often using reversed leads to nicer code.

48
votes

foo.reverse() actually reverses the elements in the container. reversed() doesn't actually reverse anything, it merely returns an object that can be used to iterate over the container's elements in reverse order. If that's what you need, it's often faster than actually reversing the elements.

14
votes

There seems to be a great difference. I really thought it's the other way round. Why is rearranging the values in a list faster than creating a new one from an iterator ?

from decorators import bench

_list = range(10 ** 6)

@ bench
def foo():
  list(reversed(_list))

@ bench
def bar():
  _list.reverse()

foo()
bar()

print foo.time
print bar.time

0.167278051376
0.0122621059418

3
votes

Without knowing real stats about performance, _list.reverse() modifies the list itself, whereas reversed(_list) returns an iterator ready to traverse the list in reversed order. That's a big difference itself.

If that's not a problem, object.reverse() seems more readable to me, but maybe you have specific speed requirements. And if reverse() does not belong to 80% of software that's consuming resources, I wouldn't bother (as a general rule of thumb).

0
votes

It is always better to use reversed() if eventually you are going to modify the list in iterator making list immutable and working with immutable data is always better especially when your doing functional programming.

0
votes
  • _list.reverse() does an in-place reversal and does not return a value
  • reversed(_list) does not change _list, but returns a reverse iterable object
  • _list[::-1] does not change _list, but returns reversed slice

example:

_list = [1,2,3]
ret1 = list(reversed(_list))
ret2 = _list[::-1] #reverse order slice
ret3 = _list.reverse() #no value set in ret3
print('ret1,ret2,ret3,_list:',ret1,ret2,ret3,_list)

_list = [1,2,3]
for x in reversed(_list):
    print(x)

output:

ret1,ret2,ret3,_list: [3, 2, 1] [3, 2, 1] None [3, 2, 1]
3
2
1