Jatin Chaturvedi
Jatin Chaturvedi

Reputation: 57

How to check if elements of a list are alternating?

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

Answers (1)

Ghost Ops
Ghost Ops

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))
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...

Upvotes: 4

Related Questions