Answer the question
In order to leave comments, you need to log in
How to write a recursive function to count elements in a list?
There is a list: .
We need a recursive function to calculate the sum of all these elements.
It's easy to do this through a loop:[1, 2, 3, 4]
def sum_el(arr):
total = 0
for x in arr:
total += x
return total
print(sum_el([1, 2, 3, 4]))
# 10
Answer the question
In order to leave comments, you need to log in
def recursion_sum(arr):
if not arr:
return 0
return arr[0] + recursion_sum(arr[1:])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question