1

In python2.7, I tried to return a reversed list directly using the below code but it didnt return anything.

Code 1:

def reverse3(nums):
    return nums.reverse()

The below code works and I am confused by the difference between Code 1 and Code 2. Please explain what's happening here.

Code 2:

def reverse3(nums):
    nums.reverse()
    return nums

2 Answers2

2

obviously, nums.reverse() does not return any value.. it just reverses the list..

mlwn
  • 1,156
  • 1
  • 10
  • 25
0

In the first thing you are passing the return type of reverse function which is None. This is due to the fact reverse() acts on the list changes the list and returns None

a=[1,2,3]

print a.reverse()
None

a
[3, 2, 1]

Where as if you did as falsetru saying you are returning a list which is the reversed order of the list and it does not change the actual list

i.e)

a=[1,2,3]

a[::-1]
[3, 2, 1]
print a
[1,2,3]
The6thSense
  • 8,103
  • 8
  • 31
  • 65