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?
Advertisement
Answer
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.