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

8th Aug 2022, 4:50 PM
Levi
Levi - avatar
3 Answers
8th Aug 2022, 5:07 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 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]))
8th Aug 2022, 7:31 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 2
Vitaly Sokol Hy, thanks for your solution but I want to know the reason for the error? Why am I getting typerror
8th Aug 2022, 5:20 PM
Levi
Levi - avatar