-2
mylist = ['banana', 'apple', 'papaya', 'cherry']
revered_list = mylist.reverse()
print(mylist)
print(revered_list)

#Output:
# ['cherry', 'papaya', 'apple', 'banana']
# None

Why is the 'None' given when the variable is printed? What really is happening behind the scene.

  • 5
    `.reverse()` reverses in-place and returns `None`. – sj95126 Jul 28 '22 at 00:49
  • 1
    In addition, if you dont need to keep a copy a your reversed list, you can do `print(reversed(mylist))`, which is a iterator that iterates the list in reversed order – goldenotaste Jul 28 '22 at 00:51
  • I don't get the order of execution, shouldn't the printed variable must give the reversed list? – Rajitha Amarasinghe Jul 28 '22 at 00:51
  • In the Python [documentation](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) about mutable sequence types, you can read that `.reverse()` modifies the sequence in place and does not return the reversed sequence. – VoidTwo Jul 28 '22 at 00:54
  • @RajithaAmarasinghe - you could try to run your code here - https://pythontutor.com/ – Daniel Hao Jul 28 '22 at 00:55
  • 1
    @Daniel Hao - WOW, that was so helpful, I didn't know about that site. I was using Thonny for the same purpose, but this layout is more comprehensive and clean I guess. Yes, I got the answer to my question. Thank you once again. – Rajitha Amarasinghe Jul 28 '22 at 01:06
  • @Daniel Hao - agree with you 100% – Rajitha Amarasinghe Jul 28 '22 at 01:09

1 Answers1

2

Because reverse() method does not return anything ( which means it return None, that explains why you get None) and reverse the list in place, so in your example, you can get reveresed list like this:

mylist = ['banana', 'apple', 'papaya', 'cherry']
mylist.reverse()
print(mylist) # you get a modified list (reversed)

if you want to make a copy of reversed list, then use reversed() function:

mylist = ['banana', 'apple', 'papaya', 'cherry']
reversed_list = reversed(mylist)
print(reversed_list)
Ghazi
  • 583
  • 5
  • 20
  • OK, now I got it, it is the difference between 'reverse' and 'reversed', your answer was loud and clear. Thank you so much for reaching out :-) – Rajitha Amarasinghe Jul 28 '22 at 00:57