Mish
Mish

Reputation: 53

How do I fix a TypeError: unsupported operand type(s) for +: 'int' and 'list'

My function is supposed to take as an input a list that contains a list of numbers. Each number list is supposed to represent the grades a particular student received for a course. For example, here is an input list for a class of four students:

[[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]

My function is supposed to print one per line, every student’s average grade. I can't assume that every student as the same number of grades.

This is what I have so far:

def avg(grades):
    for average in grades:
        return sum(grades) / len(grades)

But when I tested it out by typing avg([[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]) it shows this error:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    avg([[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]])
  File "<pyshell#3>", line 3, in avg
    return sum(grades) / len(grades)
TypeError: unsupported operand type(s) for +: 'int' and 'list'

The solution should be:

90.0
60.0
87.0
11.0

How can I fix it?

Upvotes: 1

Views: 2594

Answers (3)

U13-Forward
U13-Forward

Reputation: 71570

You need to do sum(average) and len(average), with average not grades:

def avg(grades):
    for average in grades:
        print(sum(average) / len(average))
avg([[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]])

Upvotes: 2

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4189

grades= [[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]

def avg(grades):
    for average in grades:
        print(sum(average) / len(average))
    return 
avg(grades)

Output:

90.0
60.0
87.0
11.0

Upvotes: 2

O.O
O.O

Reputation: 1298

A simple solution :

students_results = []
def avg3(students):
    for student in students:
        students_results.append(sum(student) / len(student))
    return students_results

arr = [[95, 92, 86, 87], [66, 54], [89, 72, 100], [33, 0, 0]]
print(avg3(arr))

Result : [90.0, 60.0, 87.0, 11.0]

Upvotes: 2

Related Questions