list indices must be integers or slices, not float

5k views Asked by At

I have a list, sortedInfected, which is made up of integers and with an unknown length.

When I run this script i get the error: "list indices must be integers or slices, not float".

How can i fix this?

medianList =[]
b = (len(sortedInfected) / 2)

if len(sortedInfected) % 2 == 0:

    median = (sortedInfected[b] + sortedInfected[b-1]) // 2
    medianList.append(median)
else:

    median = sortedInfected[b - 0.5]
    medianList.append(median)
1

There are 1 answers

1
Cory Kramer On BEST ANSWER

In Python 3.x, the / operator performs floating point division. If you want int division use //

b = len(sortedInfected) // 2

You could therefore change your code to

medianList =[]
b = (len(sortedInfected) // 2)

if len(sortedInfected) % 2 == 0:    
    median = (sortedInfected[b] + sortedInfected[b-1]) // 2
    medianList.append(median)
else:    
    median = sortedInfected[b]
    medianList.append(median)