Python TypeError: list indices must be integers or slices, not float Error

723 views Asked by At

I am getting a TypeError: list indices must be integers or slices, not float on the fourth line of code when I run this. nums and nums2 are simply asking the user to provide a list of numbers that will be used to calculate the inner product in the code that I have provided.

def innerproduct(nums, nums2):
    for i in nums:
        if i in nums2:
            sum +- nums[i] * nums2[i]
    return innerproduct

I'm not sure why this error is occurring and how to resolve this issue, so any guidance would be appreciated.

2

There are 2 answers

0
Shubham Periwal On

for i in nums means that i will store the value in nums list, not the index.

for example if nums = [1.5, 6.2, 0.1] then i would be 1.5 and nums[i] is throwing that error.

either you can do for i in range(len(nums)): and get nums[i] or just for i in nums and then sum += i instead of nums[i]

0
Jay Shukla On

Extending Shubham's answer,

update your code with the below snippet and your code will work

def innerproduct(nums, nums2):
    sm = 0
    for i,num in enumerate(nums): # enumerate returns index of item & actual item
        if num in nums2:
            sm += num * nums2[i]
    return sm