Python Check if List Contains Same Elements

Python check if list contains same elements | We will discuss how to check if a list contains the same items or elements. In Python, there are many methods available on the list data type that help you check the same element or not. In this post, we are using native method, set(), len(), all(), count(), groupby(), and slicing.

Check if List has Same Elements in Python

This program uses a simple understandable code of comparing each element of a list using the For Loop and if-else statement. If all the elements are equal to the first variable then the program prints ‘Equal’ else if the loop encounters that both elements are not equal then the loop will stop and prints ‘Not Equal’.

# Python program to check if list contains same elements

def check_elements(l):
    #stores first element in a variable
    element = l[0]
    x = True
      
    # Comparing each element with first item 
    for i in l:
        if element != i:
            x = False
            break;
              
    if (x == True): 
        print("Yes, all elements are equal.")
    else: 
        print("No, all elements are not equal.")            


# take list
my_list = ['Know Program', 'Know Program', 'Know Program']

# printing list
print('List:', my_list)

# calling function
check_elements(my_list)

Output:-

List: [‘Know Program’, ‘Know Program’, ‘Know Program’]
Yes, all elements are equal.

Using set() Function

Python provides a built-in function set(). The set() is the collection of unordered items. Each element in the set must be unique, immutable, and the sets remove the 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. If the length of the set is one, all elements in the list are the same. Else, the elements in the list are different.

# Python program to check if list contains same elements

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

# take list
my_list = ['Know Program', 'Know', 'Know Program']

# printing list
print('List:', my_list)

# check elements are equal or not
if (check_elements(my_list) == True):
    print("Yes, all elements are equal.")
else:
    print("No, all elements are not equal.")

Output:-

List: [‘Know Program’, ‘Know’, ‘Know Program’]
No, all elements are not equal.

Using count() Function

The count() is an inbuilt function in Python that returns the count of how many times a given object occurs in list. To check if all elements in a list are the same, you can compare the number of occurrences of any elements in the list with the length of the list.

The count() method is faster than using set() because the set method works on sequences, not iterable but the count() function simply counts the first element. This method needs to really check all elements to get the correct count.

# Python program to check if list contains same elements

res = False

def check_elements(l):
    if len(l) < 0 :
        res = True
    res = l.count(l[0]) == len(l)
              
    if (res): 
        print("Yes, all elements are equal.")
    else:
        print("No, all elements are not equal.")            


# take list
my_list = ['Know Program', 'Know Program', 'Know Program']

# printing list
print('List:', my_list)

# calling function
check_elements(my_list)

Output:-

List: [‘Python’, ‘Python’, ‘Python’]
Yes, all elements are equal.

Using all() Function

The all() is a function that takes iterable as an input and returns true if all the elements of the iterable are true. Otherwise, false. If all() function returns true means all the elements in the list are equal. Otherwise, not equal. This the simplest and most elegant way to check for condition but a bit slower than other functions.

# Python program to check if list contains same elements

res = False

def check_elements(l):
    if (len(l) < 0):
        res = True
    res = all(ele == l[0] for ele in l)
      
    if(res):
        print("Yes, all elements are equal.")
    else:
        print("No, all elements are not equal.")

# take list
my_list = ['Python', 'Python', 'Python', 'Java']

# printing list
print('List:', my_list)

# calling function
check_elements(my_list)

Output:-

List: [‘Python’, ‘Python’, ‘Python’, ‘Java’]
No, all elements are not equal.

Using slicing operator

We compare the start of the list denoted by [1:] to the end of the list denoted by [:-1].

# Python program to check if list contains same elements

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

# take list
my_list = ['Know Program', 'Know Program', 'Know Program']

# printing list
print('List:', my_list)

# check elements are equal or not
if (check_elements(my_list) == True): 
    print("Yes, all elements are equal.")
else:
    print("No, all elements are not equal.")

Output:-

List: [‘Know Program’, ‘Know Program’, ‘Know Program’]
Yes, all elements are equal.

Using groupby() Function

The groupby() method 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.

# Python program to check if list contains same elements

# import groupby function
from itertools import groupby

def check_elements(l):
    x = groupby(l)
    return next(x, True) and not next(x, False)

# take list
my_list = ['Know Program', 'Know Program', 'Python', 'Know Program']

# printing list
print('List:', my_list)

# check elements are equal or not
if (check_elements(my_list) == True): 
    print("Yes, all elements are equal.")
else:
    print("No, all elements are not equal.")

Output:-

List: [‘Know Program’, ‘Know Program’, ‘Python’, ‘Know Program’]
No, all elements are not equal.

Other Method

This program takes the first element and multiplies 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.

# Python program to check if list contains same elements

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

# take list
my_list = ['Know Program', 'Know Program', 'Know Program']

# printing list
print('List:', my_list)

# check elements are equal or not
if (check_elements(my_list) == True): 
    print("Yes, all elements are equal.")
else:
    print("No, all elements are not equal.")

Output:-

List: [‘Know Program’, ‘Know Program’, ‘Know Program’]
Yes, all elements are equal.

Also See:- Python Program to Find Duplicates in List

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *