简体   繁体   中英

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

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

if nums and nums[0] != 13:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM