Chase - 1 year ago 68
Python Question

# How To Tell if An Element In A List Is Itself A List? [Python]

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?

``````if isinstance(x, list):
Common Gotchas You shouldn't name your own variables as `list` because you then overwrite the type `list` and function `list()`
Similarly for your function `sum()`. You wouldn't want to overwrite the `sum()` function that already handles a list of numbers.