Home > Mobile >  Python recursive function that reverses a list
Python recursive function that reverses a list

Time:04-14

Picture of my code

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.

enter image description here

CodePudding user response:

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]

CodePudding user response:

No need for any recursive programming:

list_in = [1, 2, 3]
list_out = list_in[::-1]

CodePudding user response:

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

CodePudding user response:

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
  • Related