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
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.
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.
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
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).
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.
来源:https://stackoverflow.com/questions/6810036/whats-better-the-reverse-method-or-the-reversed-built-in-function