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)
Asked By: clutchcocobean

||

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.

Answered By: user2555451

x.reverse() doesn’t return the reversed list, it just reverses it. You need to separately call print(x) after you have reversed it.

Answered By: adam

you can just slice :

e = ['baby','egg','chicken']
f = e[::-1]
print(f)
Answered By: nishparadox

An easy approach with the “reversed” function:

for str in reversed(e):
    print(str)
Answered By: Heng Li
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.