I was practicing from coding bat. The question was to create a function that will return the sum of numbers in a list. However, if a number is 13 , it will be skipped and the number next to it will also be skipped. I have tried it but I am getting an error that says ‘list index out of range’. I have put the code I tried to use below. Please help. I do not understand why it doesn’t work. Edit: I tried something a bit more different and it’s given below . I still get list index out of range. However, I am not removing anything from the main list. Why doesn’t this work now? Edit 2: Tried something else. Also given below . For an input like [1,2,13,2,1,13] I am getting 6 , which is clearly wrong.
def sum13(nums):
for i in range(len(nums)):
if nums[i] == 13:
nums.remove(nums[i])
nums.remove(nums[i+1])
result = sum(nums)
return result
def sum13(nums):
result = sum(nums)
for x in range(len(nums)):
if nums[x] == 13:
result -= nums[x]
result -= nums[x+1]
return result
def sum13(nums):
result = sum(nums)
for x in range(len(nums)):
if nums[x] == 13:
result -= nums[x]
if nums[x] != nums[-1]:
result -= nums[x+1]
return result