0

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)
Peter
  • 13
  • 1
  • 2
  • If using Python 3, force integer division by using `//`. But you are also subtracting `0.5` from `b`. What do you expect this to do? If `b` is `8`, and you subtract `0.5` from it, you are left with `7.5`. How do you expect this to be used as a list index? – Tom Karzes Mar 09 '16 at 12:15
  • List indexes must be integers. You need to decide how you want to handle the cases that currently give non-integer indexes. – Tom Karzes Mar 09 '16 at 12:17
  • My thought was that i only subtracted 0.5 from b when the length was odd. That's why i put it under "else". So if len is 9, b would be 9/2 - 0.5. But that did not work. But it seems to work with Cory's script, so it's all good :) – Peter Mar 09 '16 at 12:27

1 Answers1

2

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)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • That would only work if the len(sortedInfected) is an even number. How can I get it to work with odd numbers? – Peter Mar 09 '16 at 12:16