1

Could anyone please explain to me why this is not working? The error message I'm getting is: TypeError: list indices must be integers or slices, not float.

def median(lst):
    s = sorted(lst)
    l = len(lst)/2
    if len(lst) % 2 == 0:
        print((s[l] + s[l-1])/2.0)
    else:
        print(s[l])
median([3,3,5,6,7,8,1])
vanDeurs
  • 35
  • 5
  • 1
    well... list indices must be integers or slices, not float. So force l to be an integer – FLab Apr 26 '17 at 15:38
  • 1
    You are dividing `len(lst)` by two, which yields a float. You can use integer division instead (`//`). – L3viathan Apr 26 '17 at 15:39

2 Answers2

0

If len(lst) is odd then l becomes a float.

Interestingly the code you've written is probably valid in Python 2 as it uses integer division if both the numerator and denominator are integers.

However in Python 3 true division is used by default.

For more information see: In Python 2, what is the difference between '/' and '//' when used for division? and https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator

Community
  • 1
  • 1
Will S
  • 744
  • 8
  • 17
0

error you made is in calculating l

dividing using operator / returns actual division i.e. a floating point value while // returns only quotient i.e. an integer

hence

you should calculate l as follows

l = len(lst) // 2

or convert l to int using

l  = int(l)
Ani
  • 2,848
  • 2
  • 24
  • 34