In: Computer Science
In python write a program that first creates a list with the integers 0 through 9 and then traverses that list RECURSIVELY (no for/while loops allowed) and prints out the integers on the list.
A sample Python function which iterates a given numeric list using recursion (without using loops) is given below:
#Define a function to iterate a list using recursion without loop
def iterate(lst, start, end):
#Add conditions to get out of iteration (like wrong input)
if start < 0 or end >= len(lst) or start > end:
return
#If above condition is false, print the current list element
print(lst[start])
#Continue with next iteration
iterate(lst, start + 1, end)
#Generate a list
num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#Print on screen
iterate(num_list, 0, 9)
Comments have been added for better comprehension. Our iteration function name is iterate which needs three arguments, list, start and end. The passed list elements is traversed iteratively starting from the second argument, start till third argument, end. Our list is defined as num_list from 0 to 9. We call the iterate method and pass the list (num_list), starting value (0) and end value (9) for the recursive iteration.
Screenshot of the code:
Output of program:
This is one way to iterate a list in Python recursively without using any kind of loops (for/while etc.).