'Python recursive function that reverses a list
I want to write a recursive function that reverses a list. Given an input: [1,2,3], the function should return [3,2,1]
I am however recieving this error message.
Solution 1:[1]
Try like this :
def reverse(lst,start,end):
if start>=end:
return lst
else:
temp=lst[start]
lst[start]=lst[end]
lst[end]=temp
return reverse(lst,start+1,end-1)
l = [1,2,3]
print(reverse(l,0,len(l)-1))
Output:
[3, 2, 1]
Solution 2:[2]
No need for any recursive programming:
list_in = [1, 2, 3]
list_out = list_in[::-1]
Solution 3:[3]
newList.append(temp) doesn't have a return value, and therefore returns None. newList.append(temp) adds temp to newList, so your code could work as:
def recursiveReverse(dataList):
if len(dataList) == 1:
return dataList
else:
temp = dataList.pop(0)
newList = recursiveReverse(dataList)
newList.append(temp)
return newList
Solution 4:[4]
From what I can see in the error message it is throwing an error is you are trying to append something to none type as in the line return yourlist.append(element).
Try appending to the list first and then return it.
Like
mylist.append(element)
return mylist
Solution 5:[5]
In python, lists are mutable objects, and list.append adds an element to the existing list but doesn't return anything. That's why you're getting that error.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ACHRAF |
| Solution 2 | Giovanni Tardini |
| Solution 3 | PlainXYZ |
| Solution 4 | anonymous |
| Solution 5 | jalm |
