I am running this code to find the sum of even numbers. here is my code.
from functools import reduce liste = [1,2,3,4,5,6,7,8,9,10] def cift_mi(a): if (a % 2 == 0): return True return False ciftler = (list(filter(cift_mi,liste))) def toplama(a,b): return a + b sonuc=(list(reduce(toplama,list(ciftler)))) print(sonuc)
When I run the code I receive this error:
TypeError: 'int' object is not iterable
To figure this out, look at what line the error occurs on:
Traceback (most recent call last): File "main.py", line 15, in <module> sonuc=(list(reduce(toplama,list(ciftler)))) TypeError: 'int' object is not iterable
It shows the line where the error occurs, but there are several things happening on that line, so we can break it up into separate parts:
ciftler_list = list(ciftler) reduced_value = reduce(toplama, ciftler_list) sonuc = list(reduced_value)
And now the error changes:
Traceback (most recent call last): File "main.py", line 18, in <module> sonuc = list(reduced_value) TypeError: 'int' object is not iterable
The error is saying that
list is trying to iterate a value, but that value is an int, so it can’t. That means
reduced_value must be an int. So, the
reduce function must be returning an int.
And this makes sense, because your reduce function
toplama is returning
a + b, so
reduce is going to return the sum of all the values in
ciftler. Its return value is an int, not a list, so you can’t call
list() on it.
You probably want the assignment to look like this:
# ciftler is already a list, don't need to call list() again sonuc = reduce(toplama, ciftler)