Python | Check if all items in the list are identical

Python Methods and Functions

Examples :

  Input:  ['a',' b', 'c']  Output:  False  Input:  [1, 1, 1, 1]  Output:  True 

Approach # 1 Using a loop
Run a for loop and check if the first item is identical to all other items in the list. This approach requires O (n) time complexity.

# Python3 checker
# all elements in the list are identical

def check ( list ):

return all (i = = list [ 0 ] for i in list )

 
# Driver code a

print (check ([ ' a' , 'b' , 'c' ]))

print (check ([ 1 , 1 , 1 ]))

Exit :

 False True 

Approach # 2. Using Set
Converting this list to a set removes all duplicate elements. If the size of the result set is less than or equal to 1, then the list contains all identical elements.

# Python3 checker
# all items in the list are identical

def check ( list ):

return len ( set ( list )) & lt; = 1

 
# Code driver

print (check ([ 'a' , ' b' , 'c' ]))

print (check ([ 1 , 1 , 1 ]))

Exit:

 False True 

Approach # 3: Using count ()
By counting how many times the first item appears in the list, we can check if the count is equal to the size of the list or not. Simply put, check if the first element repeats across the entire list or not.

# Python3 checker
# all items in the list are identical

def check ( list ):

return list . count ( list [ 0 ]) = = len ( list )

 
# The code driver

print (check ([ ' a' , 'b' , 'c' ]))

print (check ([ 1 , 1 , 1 ]))

Exit :

 False True 

Approach # 4: Alternative method
Another method is to take the first element and multiply it by the length of the given list to form a new list, so that the new list contains elements identical to the first elements of the given list size, and then compare it with this list.

 

# Python3 checker
# all elements in list are identical

def check (x):

return x and [x [ 0 ]] * len (x) = = x

 
# Driver code

print (check ([ 'a' , ' b' , 'c' ]))

print (check ([ 1 , 1 , 1 ]))

Exit :

 False True 

Approach # 5 Using Extended Slices
Python Fragment Notation is used to get subsets of values. Thus, we compare the beginning and end of the list with the end before the beginning of the list.

# Python3 checker
# all items in the list are identical

def check ( list ):

return list [ 1 :] = = list [: - 1 ]

 
# Driver code

pr int (check ([ 'a' , 'b' , ' c' ]))

print (check ([ 1 , 1 , 1 ]))

Exit :

 False True 




Tutorials