Ambrus Armando
Ambrus Armando

Reputation: 21

Why I get the error: list index out of range

def sum13(nums):
  summ = 0
  for i in range(1, len(nums)):
    if nums[i] != 13 and nums[i-1] != 13:
     summ += nums[i]
  if nums[0] != 13:
    summ += nums[0]
  return summ

The error is produced by the last if and I don't understand why

Upvotes: 1

Views: 69

Answers (2)

David Buck
David Buck

Reputation: 3830

If you use Python enumerate, rather than a loop counter, to track your position in the array you can simplify the code to have a single if statement, and eliminate the error if the length of the list is zero:

def sum13(nums):
    summ = 0
    for ix, num in enumerate(nums):
        if ix == 0 or (num != 13 and nums[ix-1] != 13):
            summ += num
    return summ

When nums is empty, the for loop won't execute at all.

Because Python uses 'early termination' in the evaluation of if statements, it means that as soon as it detects that ix == 0 is True, it won't evaluate nums[ix-1] when ix is 0.

Upvotes: 0

kiteant
kiteant

Reputation: 66

That means len(nums) == 0. Try something like

if nums and nums[0] != 13:

Upvotes: 4

Related Questions