简体   繁体   中英

why -1 is necessary to index error in python list index out of range for loop

index error: list out of range
lst = [1,2,3,4]
for i in range(len(lst)):
    if lst[i] == lst[i+1]:
         print(True)

if we use len(lst) - 1 it works why?

len(lst) is 4, so your range object will be over 0, 1, 2, and 3. When i is 3, lst[i+1] will be lst[4] . 4 is not a valid index for lst .

If you do range(len(lst)-1) , however, you'll be running over just 0, 1, and 2. Therefore, when i is 2, you'll be comparing the last two elements of the array, namely, lst[2] and lst[3] .

That's because python list are indexed from 0 to n-1 where n is the number of elements present in the list.

  1. The range(len(lst)) will loop from 0 to len(lst)-1 . But you are also using lst[i+1] inside the loop which makes your array access the index out of range on the last iteration and hence the error. For eg. if your list length is 4, then on the last iteration, i will be 3 and you are accessing lst[i+1] , which is lst[4] which is out of bounds of the list.

  2. When you use range(len(lst)-1) , you are only iterating from 0 to len(lst)-1 which means that even on the last iteration, you are only accessing upto lst[len(lst)-1] , that is the last index of the last and never accessing the out of bound index. Hence, this one is the correct way to iterate over the loop in your case.

Assume this is your list:

[1, 2, 3, 4]

Now when you do:

for i in range(len(lst))

The range will give you the values for i as:

0, 1, 2, 3

In this statement, when i is 3 , you also try to access the index 4 , which doesn't exist:

if lst[i] == lst[i+1]:

Hence, the exception.

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