Identify if list has consecutive elements that are equal in python

前端 未结 6 1579
情深已故
情深已故 2020-11-28 15:01

I\'m trying to identify if a large given list has consecutive elements that are the same.

So let\'s say

lst = [1, 2, 3, 4, 5, 5, 6]

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 15:32

    A simple for loop should do it:

    def check(lst):
        last = lst[0]
        for num in lst[1:]:
            if num == last:
                return True
            last = num
        return False
    
    
    lst = [1, 2, 3, 4, 5, 5, 6]
    print (check(lst)) #Prints True
    

    Here, in each loop, I check if the current element is equal to the previous element.

提交回复
热议问题