I'm trying to enumerate the list using recursion and am having a hard time doing so. If anyone can point me in the right direction that would be greatly appreciated! :)
def my_enumerate(items, start_index=0):
"""my enumerate"""
result = []
if not items:
return []
else:
a = (start_index, items[0])
result.append(a)
my_enumerate(items[1:], start_index 1)
return result
ans = my_enumerate([10, 20, 30])
print(ans)**strong text**
CodePudding user response:
Try:
def my_enumerate(items, start_index=0):
"""my enumerate"""
result = []
if not items:
return []
else:
a = (start_index, items[0])
result.append(a)
result = my_enumerate(items[1:], start_index 1) # here
return result
The following is more concise:
def my_enumerate(items, start_index=0):
"""my enumerate"""
return [(start_index, items[0])] my_enumerate(items[1:], start_index 1) if items else []
CodePudding user response:
As you are using recursion and you are declaring result = []
within a function so everytime it simply gets empty so you lose all previous results.
If you want exactly this to work there is also another way that by making the result as global if you wanted to use that list globally like below:
result = []
def my_enumerate(items, start_index=0):
"""my enumerate"""
global result
if not items:
return []
else:
a = (start_index, items[0])
result.append(a)
my_enumerate(items[1:], start_index 1)
return result
ans = my_enumerate([10, 20, 30])
print(and)
But @CocompleteHippopotamus answer will work when you don't want to use a global keyword.