0

So I just started coding and I chose python. I was working with lists and I noticed something kinda odd.

wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]

print("\n"+str(wishPlaces.reverse())) 

if I write it that way, then once executed it shows "None" as a result (I use geany IDE)

But it's okay when I write:

wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]


wishPlaces.reverse()
print("\n"+str(wishPlaces))

Can somebody help me by telling what's wrong with the previous line of code?

depperm
  • 10,606
  • 4
  • 43
  • 67
farhaaan
  • 3
  • 1
  • 2
    `wishPlaces.reverse()` doesn't return anything, so... – cs95 Apr 23 '18 at 18:43
  • `reverse` reverses the elements in place with no return, that is why you get `None` as an output in your first example – depperm Apr 23 '18 at 18:44
  • Possible duplicate of [list.reverse does not return list?](https://stackoverflow.com/questions/4280691/list-reverse-does-not-return-list) – pault Apr 23 '18 at 18:44

2 Answers2

0

The reverse() method is an in place method. This means that it doesn't return anything, it just modifies the list in place. That's why you use wishPlaces.reverse() to modify wishPlaces and NOT wishPlaces=wishPlaces.reverse() .

When you have print("\n"+str(wishPlaces.reverse())), you are telling python to print what wishPlaces.reverse() is returning, and what that method returns is None (a Nonetype object). When you modify wishPlaces in place using the .reverse() method and then print wishPlaces, things work as expected because you've actually modified wishPlaces.

enumaris
  • 1,868
  • 1
  • 16
  • 34
0

Use a list iteration instead:

wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]
wishPlaces = wishPlaces[-1:0:-1]
print(wishPlaces)

The [-1:0:-1] is an iterating syntax. First value is starting index; -1 represents the last item of your list. Second defines the finishing index. Third value defines step; -1 is reversed.

Final code:

wishPlaces = ["Tokyo","Hong Kong","New York","Paris","London"]

print("\n"+wishPlaces[-1:0:-1])

Note that you dont need to convert list items to string

Also print function automatically prints new line to console window

Jakub Bláha
  • 1,491
  • 5
  • 22
  • 43