list.reverse() is not working [duplicate]

有些话、适合烂在心里 提交于 2019-12-05 03:22:22

reverse modifies the list in place and returns None. If you do

l.reverse()
print l

you will see your list has been modified.

list.reverse() reverses the list in place. It doesn't return the reversed list. For that, use reversed() function:

print reversed(l)

Or just use the extended slice notation:

print l[::-1]

L.reverse() modifies L in place. As a general rule, Python builtin methods will either mutate or return something but not both

The usual way to reverse a list is to use

print L[::-1]

reversed(L) returns a listreverseiterator object which is fine for iterating over, but not so good if you really want a list

[::-1] is just a normal slice - the step is -1 so you get a copy starting from the end and ending with the start

The docs say

list.reverse() : Reverse the elements of the list, in place.

in place means the original list gets changed, rather than returning a new list, so the return you ask it to print is None.

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