# Python - Check if all elements in a list are identical

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

There may be occasions when a list will contain all the values which are same. In this article we will see various way to verify that.

## With all

We use the all function to find the result of comparison of each element of the list with the first element. If each comparison gives a result of equality then the result is given as all elements are equal else all elements are not equal.

## Example

Live Demo

listA = ['Sun', 'Sun', 'Mon']

resA = all(x == listA[0] for x in listA)

if resA:
print("in ListA all elements are same")
else:
print("In listA all elements are not same")

listB = ['Sun', 'Sun', 'Sun']
resB = all(x == listA[0] for x in listB)

if resB:
print("In listB all elements are same")
else:
print("In listB all elements are not same")

## Output

Running the above code gives us the following result −

In listA all elements are not same
In listB all elements are same

## With count

In this approach we count the number of occurrences of the first element and compare it with length of the elements in the list. If all elements are same then this length will match else it will not.

## Example

Live Demo

listA = ['Sun', 'Sun', 'Mon']

resA = listA.count(listA[0]) == len(listA)

if resA:
print("in ListA all elements are same")
else:
print("In listA all elements are not same")

listB = ['Sun', 'Sun', 'Sun']
resB = listB.count(listB[0]) == len(listB)

if resB:
print("In listB all elements are same")
else:
print("In listB all elements are not same")  

## Output

Running the above code gives us the following result −

In listA all elements are not same
In listB all elements are same
Updated on 10-Jul-2020 11:30:02