Recursive code to find the sum of all elements of a list in python

Karthika A
Guvi
Published in
1 min readDec 17, 2019
def findSum(list1): 
if len(list1)== 1:
return list1[0]
else:
return list1[0]+findSum(list1[1:])

# driver code
list1 =[]
# input values to list
list1 = [1, 2, 3, 4, 5]
print(findSum(list1))

findSum(list1) is recursively called until the last element of the list.

For the above sample values in the list, the recursive call goes like below,

list1 = [12,34,67,8,91]
findSum(list1,5)

list1[0]+findSum(list1[1:],)

12+findSum([34,67,8,91])

12+34+findSum([67,8,91])

12+34+67+findSum([8,91])

12+34+67+8+findSum([91])

Now length of list is 1 so it returns first element,

12+34+67+8+91 which is equal to 212 printed on the console

--

--