The problem is that when i
arrives at the last element, i + 1
tries to access an element that does not exist. Then you should only go to the penultimate element.
Another point is that you don’t need to create another list with the result of the comparisons, only to see if all the results are True
. To check if all the results are true, just use all
:
tempos = [0.5, 1.3, 2.5, 3.4]
todos_iguais = all(tempos[i] == tempos[i + 1] for i in range(len(tempos) - 1))
print(todos_iguais) # False
It is worth remembering that all
returns True
if the list is empty. If you want it to return False
for this case, have to treat separately:
# retorna False se a lista for vazia (se não for vazia, usa o mesmo código anterior)
todos_iguais = not tempos or all(tempos[i] == tempos[i + 1] for i in range(len(tempos) - 1))
But as the idea is to know if all the elements are equal, it does not matter if you are comparing the element with the next or with any other. So you could compare them all to the first:
# vê se a lista é vazia ou se todos são iguais ao primeiro
todos_iguais = not tempos or all(tempos[0] == x for x in tempos)
Now it is important to see if the list is empty, otherwise it will give error when trying to access the first element.
Of course a useless comparison will be made at the beginning (the first element will be compared to itself), but if you want you can do:
todos_iguais = not tempos or all(tempos[0] == x for x in tempos[1:])
For so I use only the second element hereafter in for
. I just don’t know if it’s worth creating another list just to avoid a comparison.
Also note that at no time do you need the variable n
.
Another alternative - maybe half over Engineered - is to use itertools.groupby
. Including, in the own documentation has the "recipe" to detect if all elements are equal:
from itertools import groupby
tempos = [0.5, 1.3, 2.5, 3.4]
g = groupby(tempos)
todos_iguais = next(g, True) and not next(g, False)
The idea is that groupby
groups consecutive elements that are equal in a single group. By calling next
the first time, it returns the first group. If the list only has equal elements, there will not be a second group, and therefore the second call of next
returns the second parameter entered, which in this case is False
(that is, I am checking if the first group exists and if the second group does not exist, which only occurs if all elements are equal).
This code also returns True
to empty list. If you want it to return False
for this case, just change the first call to next(g, False)
.
Your vector has 4 positions ranging from 0 to 3, when you do i+1, you are getting the next value, but what happens you fall at the last position, and try to get the 3+1 position, which does not exist?
– FourZeroFive