Reverse the order of a list
Question:
I need this to reverse what is in the list no mater if its numbers or words right now when I run it, it prints None
. I need it to print the reversed list. Can anyone help?
def func4(x):
print(x.reverse())
return;
e = ['baby','egg','chicken']
func4(e)
Answers:
Your code is actually working as intended; it reverses the list just fine. The reason it prints None
is because list.reverse
is an in-place method that always returns None
.
Because of this, you should be calling reverse
on its own line:
def func4(x):
x.reverse()
print(x)
e = ['baby','egg','chicken']
func4(e)
Now, print
will print the reversed list instead of the None
returned by reverse
.
Note that the same principle applies to list.append
, list.extend
, and pretty much all other methods which mutate objects in Python.
Also, I removed the return-statement from the end of your function since it didn’t do anything useful. Python functions already return None
by default, so there is no reason to explicitly do this.
x.reverse()
doesn’t return the reversed list, it just reverses it. You need to separately call print(x)
after you have reversed it.
you can just slice :
e = ['baby','egg','chicken']
f = e[::-1]
print(f)
An easy approach with the “reversed” function:
for str in reversed(e):
print(str)
I need this to reverse what is in the list no mater if its numbers or words right now when I run it, it prints None
. I need it to print the reversed list. Can anyone help?
def func4(x):
print(x.reverse())
return;
e = ['baby','egg','chicken']
func4(e)
Your code is actually working as intended; it reverses the list just fine. The reason it prints None
is because list.reverse
is an in-place method that always returns None
.
Because of this, you should be calling reverse
on its own line:
def func4(x):
x.reverse()
print(x)
e = ['baby','egg','chicken']
func4(e)
Now, print
will print the reversed list instead of the None
returned by reverse
.
Note that the same principle applies to list.append
, list.extend
, and pretty much all other methods which mutate objects in Python.
Also, I removed the return-statement from the end of your function since it didn’t do anything useful. Python functions already return None
by default, so there is no reason to explicitly do this.
x.reverse()
doesn’t return the reversed list, it just reverses it. You need to separately call print(x)
after you have reversed it.
you can just slice :
e = ['baby','egg','chicken']
f = e[::-1]
print(f)
An easy approach with the “reversed” function:
for str in reversed(e):
print(str)