简体   繁体   中英

Why am I getting a python list index error in this code?

The question is: You are given a list. Print the sum of the list numbers. If the list is empty then 0 gets printed. Also, the element 7 and the element next to it won't contribute to the sum.

def realSum(arr):
    if len(arr) == 0:
        return 0
    for i in range(len(arr)-1):
        if arr[i] == 7:
            del arr[i:i+2]
    return sum(arr)

Why is this code giving me this error:

Traceback (most recent call last):
  File "C:/Users/welcome/PycharmProjects/ko/ko.py", line 16, in <module>
    print(realSum(arr))
  File "C:/Users/welcome/PycharmProjects/ko/ko.py", line 11, in realSum
    if arr[i] == 7:
IndexError: list index out of range

This code works when using a while loop but doesn't work when using for loop. Why is that so?

range(len(arr)-1) is calculated before the loop starts to iterate. Now, lets take the following input:

arr = [7, 7, 7]

So your loop will iterate over the following i s - 0,1:

  • In the first iteration, where i=0 , the first 2 elements of arr will be deleted so there will be only one element in arr
  • In the second iteration, where i=1 , arr[i] will raise an IndexError exception because you're trying to access the second element of list of size 1.

This is a classical example of why it is a bad practice to mutate a list which you're iteration over.

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