Home > Software engineering >  Compare all elements of a list
Compare all elements of a list

Time:12-28

To illustrate my problem, imagine I have a list and I want to compare each element with the next one to check if they are the same value. The problem is that when I try to access the last element of the list and compare it with "the next one", that one is out of range, so I would get an error. So, to avoid this, I put a condition when accessing that last element, so I avoid the comparison.

list = [1, 2, 1, 1, 5, 6, 1,1]

for i in range(len(list)):
    if i == len(list)-1:
        print('Last element. Avoid comparison'')
    else:
        if list[i] == list[i 1]:
            print('Repeated')

I guess that there should be a more efficient way to do this. For instance, I was trying to set the condition in the definition of the for loop, something like this:

for i in range(len(list)) and i < len(list)-1

But that is invalid. Any suggestion about how to do this in a more efficient/elegant way?

CodePudding user response:

If you need to start from 0, you should use:

for i in range(len(list) - 1):
    if list[i] == list[i   1]:
        print('Repeated')

The parameter stop of range function is just integer, so you can use value len(list) - 1 instead of len(list) to stop iterating on last but one element.

CodePudding user response:

You can utilize the functionality of range as follows:

for i in range(1, len(list):
    if list[i-1] == list[i]:
        print('Repeated')

In this way, you won't overrun the list.

CodePudding user response:

start from one and look backwards

for i in range(1, len(list)): 
    if list[i-1] == list[i]:
        print('Repeated')

CodePudding user response:

This works!

list = [1, 2, 1, 1, 5, 6, 1, 1]

for i in range(len(list)):    
    if i 1 < len(list) and list[i] == list[i 1]:
        print('Repeated')

CodePudding user response:

  • len(list) is 8
  • range(len(list)) is 0, 1, ..., 7 but you want the for loop to skip when the index is 6 right?

so given that case ... if i == len(list)-1: this condition will be True when the index is 7 (not the index that you want)

Just change that to if i == len(list)-2:

  • Related