how to check if there are 3 consecutive same values in a list in python

You can iterate through the list with a for loop and keep track of the previous values with a variable. If you find three consecutive values that are the same, you can return True. Otherwise, return False. Here's an example:

main.py
def has_three_consecutive(lst):
    prev = None
    count = 0
    for num in lst:
        if num == prev:
            count += 1
            if count == 3:
                return True
        else:
            count = 1
        prev = num
    return False
256 chars
13 lines

This function takes a list as an argument and returns True if there are three consecutive values that are the same, and False otherwise.

You can call this function like this:

main.py
my_list = [1, 2, 2, 2, 3, 4, 5]
print(has_three_consecutive(my_list)) # True

my_list = [1, 2, 3, 4, 5]
print(has_three_consecutive(my_list)) # False
150 chars
6 lines

Here, the first call to has_three_consecutive returns True because there are three consecutive values of 2 in the list. The second call returns False because there are no three consecutive values that are the same.

related categories

gistlibby LogSnag