As an exercise, I'm creating a code which recursively sums the elements of a list, including lists within lists.
Sample list: a = [1,2,[3,4],[5,6]]
Sample result: 21
My code is as follows:
a = [1,2,[3,4],[5,6]]
def sum(list):
if len(list[0]) == 1 and len(list) ==1: # case where list is [x]
return list[0]
elif len(list[0]) == 1 and len(list) > 1: # case where list is [x, etc]
return list[0] + sum(list[1:])
elif len(list[0]) > 1 and len(list == 1): # case where list is [[x,etc]]
return sum(list[0])
else: # case where list is [[x, etc], etc]
return sum(list[0]) + sum(list[1:])
print (sum(a))
However, when I try to run this I get the error "object of type 'int' has no length." I was under the impression that list[0] would just have a length of 1 if it's not a list in itself, but obviously, that doesn't work. What should I be doing instead to check whether an element in a list is itself a list?