What's "better" the reverse method or the reversed built-in function?
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
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.