Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python test Average Calculator returen error 'list' object has no attribute 'len'

Tags:

python

Hey this is a demo to show some of my classmates an intro to python and coding. The code below should be able to take a list like [0,1] and if run using the average function would return 0.5. When run using a list the function below returns the error 'list' object has no attribute 'len'. How would I get this function to work without removing the len() function

def average(lst):
    total = 0
    for item in lst:
        total += item
    averageGrade= total / lst.len()
    return averageGrade

How would I also get it to return a float rather than an integer

like image 399
Ragnar Avatar asked Jan 09 '14 20:01

Ragnar


2 Answers

Change the line

averageGrade= total / lst.len()

to

averageGrade= total / len(lst)

Refer the python docs for the built-in len. The built-in len calculates the number of items in a sequence. As list is a sequence, the built-in can work on it.

The reason it fails with the error 'list' object has no attribute 'len', because, list data type does not have any method named len. Refer the python docs for list

Another important aspect is you are doing an integer division. In Python 2.7 (which I assume from your comments), unlike Python 3, returns an integer if both operands are integer.

Change the line

total = 0.0

to convert one of your operand of the divisor to float.

like image 57
Abhijit Avatar answered Sep 20 '22 05:09

Abhijit


or by changing

averageGrade= total / lst.len()   

to:

averageGrade= total / lst.__len__()
like image 22
Harvester Haidar Avatar answered Sep 20 '22 05:09

Harvester Haidar