You can use all() methods to check if a list contains the same elements in Python. Comparing each element using for loop is also one solution to this problem.
Example how to checks if a list contains the same elements in Python
Simple example code.
Using all() method
The all() method applies the comparison for each element in the list. If all same then return true.
lst = ['A', 'A', 'A', 'A'] result = all(element == lst for element in lst) print(result)
Using for Loop
In this method, we are comparing each element. Take the first element from the list and use a for loop to keep comparing each element with the first element.
def check_list(lst): ele = lst chk = True # Comparing each element with first item for item in lst: if ele != item: chk = False break if not chk: print("Not equal") else: print("Equal") # Test code lst = ['A', 'A', 'A', 'A'] check_list(lst)
Using Count() method
A simple count of how many times an element occurs in the list. If its occurrence count is equal to the length of the list, then it means all elements in the list are the Same i.e.
lst = ['A', 'A', 'A', 'A'] result = lst.count(lst) == len(lst) print(result)
Do comment if you have any doubts and suggestions on this Python list tutorial.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.