简体   繁体   中英

How to resolve Python: IndexError: list index out of range?

I am trying to count the occurrence of '-1' in the list 'args'. '-1' occurs at many locations, so when ever it occurs more than once consecutively, I wish to count that.

I am getting an "list index out of range" error, however it is wrong. I am trying to access the 16th element, the length of 'args' is 19. On line 5 and 6 I am individually printing the index and the element of the list, these lines are executing without error.

Why am I getting the error? Moreover, print statement in line 10 is not printing, what is the reason?

args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]
i=0
while  i<= len(args)-1:
    count=0
    print(i)
    print(args[i])
    while args[i]==-1:
        count+=1
        i+=1 
    print("count="+str(count)+"-"+str(i))
    i+=1


$python main.py
0
-3
count=0-0
1
-1
count=4-5
6
-1
count=2-8
9
-1
count=4-13
14
-1
count=1-15
16
-1
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    while args[i]==-1:
IndexError: list index out of range

In your inner while loop you need to check it to prevent i out of args range

args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]
i=0
while  i<= len(args)-1:
    count=0
    print(i)
    print(args[i])
    while i <= len(args)-1 and args[i]==-1: # here to modify your code
        count+=1
        i+=1 
    print("count="+str(count)+"-"+str(i))
    i+=1

working demo

The main problem here happens when you do while args[i] == -1 .

The reason that is problematic is because if your last value will be -1 , you will increment the index and then you'll try to access args in an index that does not exist.

There is a much faster solution for your general problem (counting consecutive values), as answered by @Karin here :

from itertools import groupby
list1 = [-1, -1, 1, 1, 1, -1, 1]
count_dups = [sum(1 for _ in group) for _, group in groupby(list1)]
print(count_dups)

The IndexError is because of your Inner while loop. You are incrementing i without having a check if it exceeds the list length and trying to access it.

There's another way to solve this.

You could keep track of previously accessed element , check if it's -1 and check if previous and current element are same and only then increase the counter count

args=[-3, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1, -1, -1, -3, -1, -2, -1, -1, -1]

prev = args[0]
count = 0 
i = 1
while  i < len(args):
    if args[i] == -1 and args[i] == prev:
        count += 1
    else:
        if count > 1:
            print(count)
        count = 1
    prev = args[i]
    if i == len(args) - 1 and count > 1:
        print(count)
    i+=1

This will print the count of -1 s that occur consecutively in the list.

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