How to check if elements of a list are alternating?

Viewed 172

I have lists like this, and I want to know if their elements are alternating. For example:

list1 = ['A', 'C', 'A', 'C', 'A', 'C']  # result = True
list2 = ['A', 'A', 'A', 'C', 'A', 'C']  # result = False
list3 = ['A', 'C', 'C', 'C', 'A', 'C']  # result = False
list4 = ['A', 'C', 'A', 'C', 'A', 'A']  # result = False
  • Elements of the list will always be a string.
  • The length of this string is not fixed.
  • The list will always contain only two distinct values.

Now, How to check if elements of list are alternating in Python?

1 Answers

Try this Code:

a = ['A','C','A','C','A','C']
print((len(set(a[::2])) == 1) and (len(set(a[1::2])) == 1))

Example:

lists = [
    ['A','C','A','C','A','C'],
    ['A','A','A','C','A','C'],
    ['A','C','C','C','A','C'],
    ['A','C','A','C','A','A']
]
for i in lists:
    print((len(set(i[::2])) == 1) and (len(set(i[1::2])) == 1))
Edit: based on Daniel Hao's commments:
for sub in lists:
    print(all(x!= y for x, y in zip(sub, sub[1:])))

Output:

True
False
False
False

Tell me if its not working...

Related