Skip to content

Why am I getting TypeError: list indices must be integers or slices and not the float value while finding Median of two sorted arrays?

I have two sorted arrays and I am trying to find median of two sorted arrays.For example,if input is nums1 = [1,3], nums2 = [2] then the output will median=2.00000 and if the input is p = [1,2], t = [3,4] then the output will be median=2.50000 I have added both the arrays together and sorted them and later by using their lengths I have tried to calculate the correct value. Below is my code

class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):


    if len(nums1)%2 ==0:
        a = len(nums1)/2
        return float(nums1[a]+nums1[a-1])/float(2)
        a = len(nums1) / 2
        return float(nums1[a])

if __name__ == "__main__":
p = [1,3]
t = [2]

Below is the error in the logs.

 return float(nums1[a])
TypeError: list indices must be integers or slices, not float




Division of integers yields a float

but you could trivially check this by printing out a just before using it as an index. And the error is extremely clear that a is a float at that point.

Either coerce it to int, as


or use floor division, with

a = len(nums1) // 2
User contributions licensed under: CC BY-SA
4 People found this is helpful