The first thing to keep in mind is that in Python indexing starts at 0, so the first item has an index of 0 and the last% co_of%, that is,% co_of%.
On the other hand, if you compare one element with the next, the last item in the list can not be compared because it does not have a "following". If you make el número de elementos menos uno
, with len(indexable) - 1
the last index of the list you will have a codcadena[k+1]
, this is the cause of the exception you show.
On the other hand you use k
as control variable of IndexError
, also of k
and also increase the value manually with while
.
If what you want is to detect when an item is different from the one that follows it is much simpler:
codcadena = [0, 0, 0, 0, 1, 1, 1, 5, 5, 7, 7, 7, 9, 9, 9, 9, 8, 8, 8, 5, 5, 5]
for i in range(len(codcadena) - 1):
if codcadena[i] != codcadena[i + 1]:
print(f"{codcadena[i]} (Indice {i}) -- {codcadena[i + 1]} (Indice {i + 1})")
Notice that we generate the indexes from 0 to number of items - 2. In this case, that the list has 22 elements for
generates from 0 to 20, remember that if the list is 22 elements the last index is 21 We do not want to generate 21 because we want to compare the penultimate item (index 20) with the last (index 21) and finish, so the last iteration is:
if codcadena[20] != codcadena[20 + 1]:
If we did k = k + 1
this last iteration would be:
if codcadena[21] != codcadena[21 + 1]:
Which causes your error, since a list of 22 items does not have index 22, since the first index is 0, not 1.
The output for the example would be:
0 (Index 3) - 1 (Index 4)
1 (Index 6) - 5 (Index 7)
5 (Index 8) - 7 (Index 9)
7 (Index 11) - 9 (Index 12)
9 (Index 15) - 8 (Index 16)
8 (Index 18) - 5 (Index 19)
Instead of the range
, you can do what you would like to do in your range(len(codcadena))
.