0

How can I check if a list has alternate elements equal in python?

How can I check if a list has alternate elements equal in python?

6th Apr 2020, 4:40 AM
Ridhi Ratan
Ridhi Ratan - avatar
3 Answers
+ 2
mylst = [2, 2, 2, 7, 7, 8] You can use set(mylst) to see if any change occurs. What set does is that it removes any duplicates. If mylst's and set(mylst)'s lengths are same then and no change occurred (no duplicate found) means mylst has no duplicates, otherwise it has.
6th Apr 2020, 6:23 AM
maf
maf - avatar
+ 2
maf is right. But if what you want is two successive elements being equal; then using set method will catch list like [2, 3, 2, 4], whereas there are no equal successive elements. In such case, use regex like this... import re def check_succcessive(lst): pattern = r".*(.)\1" lst = [str(i) for i in lst] lst = "".join(lst) if re.match(pattern, lst): return True return False #Hope it helps
6th Apr 2020, 7:07 AM
Jolomi Tosanwumi