Why am I getting an error in the following code ? | Sololearn: Learn to code for FREE!

0

Why am I getting an error in the following code ?

def nestedEvenSum(obj, s=0): result = [] for key in obj: if type(obj[key]) is int and obj[key]%2==0: result.append(obj[key]) elif type(obj[key]) is dict: result = result + nestedEvenSum(obj[key]) return sum(result) obj = { "a": 2, "b": {"b": 2, "bb": {"b": 3, "bb": {"b": 2}}}, "c": {"c": {"c": 2}, "cc": 'ball', "ccc": 5}, "d": 1, "e": {"e": {"e": 2}, "ee": 'car'} } print(nestedEvenSum(obj)) In line 7 I am getting an error saying TypeError: can only concatenate list (not "int") to list

8/8/2022 4:50:10 PM

Levi

3 Answers

New Answer

+4

https://code.sololearn.com/cw0yI2Cg3Prl/?ref=app

+3

Your func on elif brunch returns int sum and can't adds to array, only in a such way: result += [ nestedEvenSum(obj[key])) ], or use result.append(nestedEvenSum(obj[key]))

+2

Vitaly Sokol Hy, thanks for your solution but I want to know the reason for the error? Why am I getting typerror