# Python : Check if all Elements in a List are Same or Matches a Condition

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Example:

Input:

givenlist = ['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]

Output:

All the elements are equal

Given a list, the task is to check if all elements in a list are same or matches the given condition

## Check that all items in a list are identical

There are several ways to check if all elements in a list are same or matches a condition some of them are:

### Method #1:Using all() function

any():

If any of the items is True, this function returns True. If the array is empty or all of the values are false, it returns False. Any can be thought of as a series of OR operations on the iterables provided.

Let’s convert the list to Iterable and check that each iterable entry is the same as the first list element using all ()

Below is the implementation:

# given list
givenlist = ['BTechGeeks', 'BTechGeeks',
'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]
# checking if all the elements are equal using all() function
if(any(element == givenlist for element in givenlist)):
print("All the elements are equal")
else:
print("All the elements are not equal")


Output:

All the elements are equal

### Method #2:Using set()

• Set includes only single elements.
• Convert the list to set and check whether the length of the set is 1.
• If the length of given set is 1 the print all the elements are equal
• else print all the elements are not equal

Below is the implementation:

# given list
givenlist = ['BTechGeeks', 'BTechGeeks',
'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]
# converting given list to set
setlist = set(givenlist)
# if the length of given set is 1 then print all the elements are equal
if(len(setlist) == 1):
print("All the elements are equal")
else:
print("All the elements are not equal")


Output:

All the elements are equal

### Method #3:Using count() function

Count() returns to the list the number of times the item is appeared.

Let’s call the list’s count() function with the first element as an argument. If the number of times it appears in the list equals the length of the list, it means that all of the elements in the list are the same.

Below is the implementation:

# given list
givenlist = ['BTechGeeks', 'BTechGeeks',
'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]
# using count function
if(givenlist.count(givenlist) == len(givenlist)):
print("All the elements are equal")
else:
print("All the elements are not equal")


Output:

All the elements are equal

Related Programs: