Python Forum

Full Version: Average of lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi I want to know how to return the average of multiple lists

What am I doing wrong here? My code needs to be defined the way it is: average(m: List[List[int]]) -> float:
Then python keeps saying Lists is not defined...

def average(m: List[List[int]]) -> float:
    """
    Examples
    >>> average([])
    0
    >>> m = [[1,2,3],[4,5,6],[7,8,9]]
    >>> average(m)
    5.0
    >>> m = [[1,2,2,5],[4,5,4,8],[7,9,9,1],[1,2,1,4]]
    >>> average(m)
    4.0625
    """
    Lists = []
    for x in m:
        
    averages = sum(m) / len(m)
    return averages

def average(m: List[List[int]]) -> float:
"""
Examples
>>> average([])
0
>>> m = [[1,2,3],[4,5,6],[7,8,9]]
>>> average(m)
5.0
>>> m = [[1,2,2,5],[4,5,4,8],[7,9,9,1],[1,2,1,4]]
>>> average(m)
4.0625
"""
averages = sum(m) / len(m)
return averages

Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
def average(m: List[List[int]]) -> float:
NameError: name 'List' is not defined


Sorry about that, its my first time here Im getting used to it.
I also deleted the codes
Lists = []
for x in m:

I know I'm supposed to use something like this for lists but I dont know how to since there is multiple lists.
First off, your indentation is incorrect. As you've posted it, it cannot generate an import error. The last two lines need to be indented further.

As for the problem you mentioned - you should either remove the type annotations, or add an import for List
from typing import List
I would save the output as float later on in the code
for example where you count average
but I'm just a beginner

Isn't there a syntax error in the first line? Why is there : ? Did you get the first line from your teacher?
This will also give you an error on a nested list
averages = sum(m) / len(m)