0

I need to access the next element of an array to compare it with the previous one, try to do it by indexes however the index is out of range

lista =  [1,2,2,3,4,5,5,6,7,8]
for i in range(len(lista)):
if lista[i]==lista[i+1]: print("same number")
2
  • 1
    you should use len(lista)-1 since the last element has no next Commented Mar 10, 2020 at 1:04
  • What is the maximum value that i will be assigned here? If it is out of range of lista, then perhaps change the loop so that it never has a value greater than the largest index. Commented Mar 10, 2020 at 1:06

2 Answers 2

4

You can zip the list with itself offset by one and avoid the indices altogether:

lista =  [1,2,2,3,4,5,5,6,7,8]
for a, b in zip(lista, lista[1:]):
    if a == b: 
        print("same number", a, b)

Prints:

same number 2 2
same number 5 5

Sign up to request clarification or add additional context in comments.

Comments

0

You can simply check the size of the list before doing the process. check the code bellow

for i in range(len(lista)):
if i == len(lista)-1:
    print("end Process")
else:
    a = lista[i]
    b = lista[i+1]
    if a == b:
        print( str(a) + " and " + str(b) + " are the same number ")

or using len(lista)-1 in your for loop

for i in range(len(lista)-1):
        a = lista[i]
        b = lista[i+1]
        if a == b:
            print( str(a) + " and " + str(b) + " are the same number ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.