27

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

Ragnar
  • 1,442
  • 3
  • 16
  • 27
  • If you want to get the length of a collection as a method of this collection, you can use `lst.__len__()`. It sometimes comes handy if you want to chain operators. – Jacquot Jun 25 '17 at 10:19

3 Answers3

67

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.

Abhijit
  • 62,056
  • 18
  • 131
  • 204
4

or by changing

averageGrade= total / lst.len()   

to:

averageGrade= total / lst.__len__()
Harvester Haidar
  • 531
  • 7
  • 16
1

Just change lst.len() to len(list)

Also can refer Progamiz Python - len for more information