Python check if list contains same elements | Example code

You can use all() methods to checks 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[0] for element in lst)

print(result)

Output:

Python check if list contains same elements

Using for Loop

In this method, we are comparing each elements. 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[0]
    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)

Output: Equal

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[0]) == len(lst)

print(result)

Output: True

Do comment if you have any doubts and suggestions on this Python list tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.