Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list.
Example :
Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22
Approach :
- Create a list.
- Create a loop for range size – 2.
- Check if the element is equal to the next element.
- Again check if the next element is equal to the next element.
- If both conditions are satisfied then print the element.
Example 1 : Only one occurrence of a 3 consecutively occurring element.
# creating the arrayarr = [4, 5, 5, 5, 3, 8] # size of the listsize = len(arr) # looping till length - 2for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i]) |
Output :
5
Example 2 : Multiple occurrences of 3 consecutively occurring elements.
# creating the arrayarr = [1, 1, 1, 64, 23, 64, 22, 22, 22] # size of the listsize = len(arr) # looping till length - 2for i in range(size - 2): # checking the conditions if arr[i] == arr[i + 1] and arr[i + 1] == arr[i + 2]: # printing the element as the # conditions are satisfied print(arr[i]) |
Output :
1 22
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


