You are looping such that you test not list == 'X'
then not range(2, 4) == 'X'
; obviously, neither is equal, so you print both times. Your logic can be dramatically simplified though. If the goal is to see if indices 2, 3 and 4 are all equal, just convert that slice of the list to a set
and check if the length is 1:
mylist = ['X', 'Y', 'X', 'X', 'X', 'Y'] # Changed list name; naming the list "list" leads to tears
if len(set(mylist[2:5])) == 1:
print("2, 3 and 4 equal")
else:
print("At least one not equal to the others")
You may also wish to check that mylist
is long enough (slicing will not raise an error if the slice doesn't get the three elements expected), as written this only tests that the list is at least 3 elements long and any elements from index 2 to 4 are equal if they exist.
If you know mylist
will always have at least five elements, and you prefer an exception when it is not, another solution is to check:
if mylist[2] == mylist[3] == mylist[4]:
print("2, 3 and 4 equal")
else:
print("At least one not equal to the others")
It's more verbose, but Python's chained comparisons mean you only load each value once, and unlike the other solution, it short-circuits; if index 2
is not equal to index 3
, it won't even bother to load index 4
, let alone compare it to the others.