What's “better” the reverse method or the reversed built-in function?

我怕爱的太早我们不能终老 提交于 2019-11-30 12:19:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!