Reversing a list with single element gives None
Question:
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].
Answers:
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
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].
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