Python - Check if all elements in a List are same

PythonServer Side ProgrammingProgramming

Sometimes we come across the need to check if we have one single value repeated in a list as list elements. We can check for such scenario using the below python programs. There are different approaches.

Using for Loop

In this method we grab the first element from the list and use a traditional for loop to keep comparing each element with the first element. If the value does not match for any element then we come out of the loop and the result is false.

Example

 Live Demo

List = ['Mon','Mon','Mon','Mon']
result = True
# Get the first element
first_element = List[0]
# Compares all the elements with the first element
for word in List:
   if first_element != word:
      result = False
      print("All elements are not equal")
      break
   else:
      result = True
   if result:
      print("All elements are equal")

Running the above code gives us the following result −

All elements are equal
All elements are equal 
All elements are equal 
All elements are equal

Using All()

The all() method applies the comparison for each element in the list. It is similar to what we have done in first approach but instead of for loop, we are using the all() method.

Example

 Live Demo

List = ['Mon','Mon','Tue','Mon']
# Uisng all()method
result = all(element == List[0] for element in List)
if (result):
   print("All the elements are Equal")
else:
   print("All Elements are not equal")

Running the above code gives us the following result −

All the elements are not Equal

Using Count()

The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.

Example

 Live Demo

List = ['Mon','Mon','Mon','Mon']
# Result from count matches with result from len()
result = List.count(List[0]) == len(List)
if (result):
   print("All the elements are Equal")
else:
   print("Elements are not equal")

Running the above code gives us the following result −

All the elements are Equal
raja
Published on 19-Dec-2019 17:04:34
Advertisements