I'm looking to reverse a list using recursion in python. I succeeded in doing so but the output isn't exactly what I wanted. trying to figure out where i'm going wrong.
def revlist(ls):
newlist = []
n = len(ls)
if n == 1:
return ls[-1]
else:
return ls[-1],revlist(ls[:-1])
This is my output.
revlist([1,2,3,4])
(4, (3, (2, 1)))
What i'm really hoping to get is this:
revlist([1,2,3,4])
(4,3,2,1)
You're closeish.
def revlist(ls):
newlist = []
n = len(ls)
if n == 1:
return [ls[-1]]
else:
return [ls[-1]] + revlist(ls[:-1])
Or cleaned up:
def revlist(ls):
if len(ls) < 1:
return []
else:
return [ls[-1]] + revlist(ls[:-1])
Basically, you need to always return a list
from your function, and append recursive calls appropriately.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.