
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Check if all elements in a List are same
In Python, a list is a collection of ordered and mutable elements enclosed in square braces[]. Each element in a list has a unique position index, starting from 0. It can accept duplicate elements.
In some cases, we may need to check if all the elements in a list are identical or not to detect a special condition in algorithms. Let's go through the different methods to check if all elements in a list are the same or not.
Using set() function
The Python set() function (built-in) is an unordered collection of unique elements. To check if all elements in a list are the same, we have to convert the list into a set so that any duplicates are automatically removed.
Example
Following is the example, in which we are using the set() function to check if all elements in a list are the same -
my_list = [100, 100, 100, 100] if len(set(my_list)) == 1: print("All elements are the same.") else: print("Elements are not the same.")
Following is the output of the above example -
All elements are the same.
Using a for loop
A for loop in Python is used to iterate through elements of a data structure, such as a list, string, etc.
To verify all the elements are equal, we need to iterate through all the elements in an array, compare the current element with the first element if they are not, all the elements in the array are not the same.
Example
Following is an example, in which we are using a for loop to check if all elements in a list are the same -
my_list = [100, 100, 100, 100] first = my_list[0] all_same = True for item in my_list: if item != first: all_same = False break if all_same: print("All elements are the same.") else: print("Elements are not the same.")
Here is the output of the above example -
All elements are the same.
Using all() function
The all() is a built-in function in Python that returns True if all elements in an iterable are true.
To check if all elements in a list are the same, we can use all() along with a generator expression to compare each item in the list with the first element. If any item is different, all() will return, or else return False.
Example
Below is an example in which we are using the all() function to check if all elements in a list are the same -
my_list = [100, 100, 100, 100] if all(item == my_list[0] for item in my_list): print("All elements are the same.") else: print("Elements are not the same.")
Below is the output of the above example -
All elements are the same.