-2

I'm following a tutorial which asks me to reverse the list in alphabetical order and then print it. I wrote this code:

visit_list = ["Alaska", "Norway", "Canada", "Germany", "Russia"]
print(visit_list)
print(sorted(visit_list))
print(visit_list)

The problem arises when I try to do it how I thought would work (which it kinda did) by doing the following.

visit_list.sort()
print(visit_list.reverse())

Now this did reverse the list, but the output code came out as simply "None". Why?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

0
visit_list.reverse()

Is a method which reverses the list but doesn't return anything it just do the reversing on the calling list which is visit_list.

So when this line executes:

print(visit_list.reverse())

It prints None because it is the returning value from executing that method which is None as it doesn't return anything to the line in which it was called.

But it actually does its job to reverse the list but simply doesn't return any value.

You can read more about the return statement which is used inside of a function to return a value to the caller (https://realpython.com/python-return-statement/).

So a quick fix to your code is simply to print the list after it was reversed using the reverse method:

visit_list.reverse()
print(visit_list)
Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18