Home > OS >  Why do I get an IndexError when counting values in a list and adding the result to another list?
Why do I get an IndexError when counting values in a list and adding the result to another list?

Time:01-31

arr2 = [2, 3, 3, 1, 2, 2, 9, 4, 4]

quantity = []
for i in range(len(arr2)-1):
    if arr2[i] == arr2[i 1]:
        quantity[i]  = 1
    else:
        quantity.append(1)

print(quantity)

I want to check if the current value is the same as the next value within the arr2 list. If it's not the same then add the number 1 to the quantity list, if it's the same then add 1 to the quantity and skip the next value.

Expected outcome:

quantity = [1,2,1,2,1,2]

Actual:

    quantity[i]  = 1
IndexError: list index out of range

CodePudding user response:

I don't understand what you really want but this solution work as you expect

arr2 = [2, 3, 3, 1, 2, 2, 9, 4, 4]
quantity = []
skip = False
for i in range(len(arr2)-1):
    if skip:
        skip = False
        continue
    if arr2[i] == arr2[i 1]:
        quantity.append(2)
        skip = True
    else:
        quantity.append(1)
print(quantity)

CodePudding user response:

It does not work because i is the index of arr2, but in your loop, when arr2[i] == arr2[i 1]: you use it with quantity, but when i equals 1 (the first 3 in arr2), arr2[i] == arr2[i 1]: is True, so you try to access quantity with an index of 1, but at this moment, quantity has only one element, so you can only acces it with an index of 0, not with an index of 1.

To do what you want you should use this:

from itertools import groupby
list1 = [2, 3, 3, 1, 2, 2, 9, 4, 4]
count_dups = [sum(1 for _ in group) for _, group in groupby(list1)]
print(count_dups)

This is from @Karin here: how to count consecutive duplicates in a python list

You could take a look here too: What's the most Pythonic way to identify consecutive duplicates in a list?

And if you want to resolve this problem by yourself with a for loop as you tried, the solution would be to create a temporary variable and increment its value until the next element is different from the previous one and then append this variable to quantity.

  •  Tags:  
  • Related