Reputation: 57
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
Now, How to check if elements of list are alternating in Python?
Upvotes: 1
Views: 783
Reputation: 1734
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))
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...
Upvotes: 4