arniem
arniem

Reputation: 145

TypeError: 'int' object is not iterable " What am I doing wrong? "

A simple program to calculate average of elements of same indices of given number of lists and print the result. For example, if -

def avg(L1, L2, L3):

    res = []

    for i in L1:
        for j in L2:
            for k in L3:
                res.append((i+j+k)/3)
                break

L1 = [1, 7, 9]
L2 = [2, 3, 8]
L3 = [4, 5, 10]


for elt in map(avg, L1, L2, L3):
    print(elt)

Output: TypeError: 'int' object is not iterable

Upvotes: 0

Views: 253

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

The problem is, that the function avg() is expecting 3 lists from the map(). But map() doesn't function that way and instead it provides one element from each iterable, which is int. You can try this code:

def avg(*items):
    return sum(items) / len(items)

L1 = [1, 7, 9]
L2 = [2, 3, 8]
L3 = [4, 5, 10]


for elt in map(avg, L1, L2, L3):
    print(elt)

Prints:

2.3333333333333335
5.0
9.0

Upvotes: 1

Related Questions