Signup/Sign In

Check if all elements in a List are same

In this article, we will learn to check that all elements in a list are the same or not in Python. We will use some built-in functions, simple algorithms, and some custom code as well to better understand the problem. Let's first have a quick look over what is a list in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]

Python supports many built-in functions to perform this task. We will look at the following ways in which we can check if all the elements present in a list are equal or not.

  1. Using all() function
  2. Using set data type
  3. Using count() function
  4. Using Brute Force Approach
  5. By multiplying elements
  6. Using Slicing method
  7. Using itertools module

Example: Check all List by Using all() Function

This example uses built-in all() function. This the simplest and most elegant way to check for condition but a bit slower than other functions. This function even works with the empty list because this is one of the few cases where python has lazy semantics. In the given example, all() function first convert the input list into iterable and then compares each element of the given list and check if they are equal or not. The program will print 'Equal' if all elements are the same else it will print 'Not Equal'.

r = False

def check(l):
    if(len(l) < 0):
        r = True
    r = all(ele == l[0] for ele in l)

    if(r):
        print("Equal")

    else:
        print("Not Equal")

#input list        
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#function call
check(list1)
check(list2)


Equal
Not Equal

Example: Check all List by Using set() Function

This example uses a built-in Python set datatype. Set does not allow duplicate elements. It also requires all of your elements to be hashable. Using this property of set, we can check whether all the elements in a list are the same or not. In this example, the list is converted to a set by passing the list name to set() method as shown below. Set will check for each element and if all the elements in the original list are identical then the set will have just one unique element. The program will return 'Not Equal' if your list has different elements else it will return 'Equal'.

def check(l):
    return len(set(l)) == 1

#input lists
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#check for condition
if(check(list1) == True): 
       print("Equal")
else: 
       print("Not Equal")

if(check(list2) == True): 
       print("Equal")
else: 
       print("Not Equal")


Equal
Not Equal

Example: Check all List by Using count() Function

This example uses count() function. This method is faster than using set() because the set method works on sequences, not iterables but count() function simply counts the first element. This method needs to really check all elements to get the correct count. This function assumes the list is a non-empty list. In this example, two functions (count,len) are used and both have an easy implementation.

Therefore, if we have the same element repeated in the list then the length of the list using len() will be equal to the number of times the element is present in the list using the count().

r = False

def check(l):
    if(len(l) < 0):
        r = True
    r = l.count(l[0]) == len(l)

    if(r):
        print("Equal")
    else:
        print("Not Equal")

#input lists
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#function call
check(list1)
check(list2)


Equal
Not Equal

Example: Check all List by Using Brute Force Approach

This algorithm uses a simple understandable code of comparing each element of a list using for loop. In this example, the first element of the list is stored in a variable. Then, using for loop each element is compared with the first variable (first element) and if the loop encounters that both elements are not equal then the loop will stop and prints 'Not Equal' else if all the elements are equal to the first variable then the program prints 'Equal'.

def check(l):
    #stores first element in a variable
    first = l[0]
    x = True

    #Comparing each element with first item 
    for ele in l:
          if(first != ele):
                 x = False
                 break;    
    if(x == True): 
          print("Equal")
    else: 
          print("Not Equal")            

#input lists
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#function call
check(list1)
check(list2)


Equal
Not Equal

Example: Check all List By multiplying the elements

This method is an alternative method and it is faster than the set method. It is a one-liner code. In this example, the program takes the first element and multiply it with the length of the given list to form a new list. So that the new list contains identical elements to the first elements of the given list size, and then compare it with the given list. This method returns True if elements are equal else False.

def check(l):
    return l and [l[0]]*len(l) == l

#input lists
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#function call
print(check(list1))
print(check(list2))


True
False

Example: Check all List by Using the Slicing method

This example uses the List Slicing operation where a list is sliced depending upon the index passed and a subset of values is retrieved. In this example, we compare the start of the list denoted by [1:] to the end of the list denoted by [:-1]. This method returns True if elements are equal else False.

def check(l):
    return l[1:] == l[:-1]   

#input lists
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#function call
print(check(list1))
print(check(list2))


True
False

Example: Check all List by Using itertools Module

This method uses groupby() function from itertools module. This function has a few properties that make it different from others. It will stop consuming items from the iterable as soon as it finds the first non-equal item. It does not require items to be hashable. It is lazy and only requires O(1) additional memory to do the check. This method returns True if elements are equal else False.

#import groupby function
from itertools import groupby

def check(iterable):
    x = groupby(iterable)
    
    return next(x, True) and not next(x, False)

#input lists
list1 = ['bat', 'bat', 'bat', 'bat']
list2 = [1, 3, 7, 1]

#function call
print(check(list1))
print(check(list2))


True
False

Conclusion

In this article, we learned to check whether all elements in the list are the same or not by using several built-in functions such as all(), groupby(), count() and other alternate methods. We used some custom codes as well. We learned about the differences between these methods in terms of processing speed.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.