Reversing a list with single element gives None [duplicate]

混江龙づ霸主 提交于 2019-12-11 18:15:43

问题


I noticed odd behaviour when returning a list (with a single element) from a function and then trying to reverse it, using reverse()

I've distilled it here:

def myFunction():
  return ["The Smiths"]

nums = [5,4,3,2,1]
nums.reverse()
print nums # 1,2,3,4,5 - fine!

# lets use one element in a list
something = ["Gwen Stefani"]
something.reverse()
print something # ["Gwen Stefani"] also fine

# now let's do the same, but from a function
a = myFunction()
print a # The Smiths
print a.reverse() # None
print a[::-1] # The Smiths

I need a grown-up to explain what is going on to create the None instead of the single element as seen with [::-1].


回答1:


list.reverse() reverses the list in-place, but the function itself doesn't return anything.

a = ["The Smiths"]
print a # The Smiths
print a.reverse() # None
print a # It's already there


来源:https://stackoverflow.com/questions/52465425/reversing-a-list-with-single-element-gives-none

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