Skip to content

Python check if list contains same elements | Example code

  • by

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[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 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[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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading