Check if all items in a list are identical in Python
This post will discuss how to check if all elements in a list are identical in Python.
1. Using Set
A simple and fairly efficient solution is to convert the list to a set. Since the set data structure does not permit duplicates, the resultant set’s length would be 1 when all the list elements are equal.
|
1 2 3 4 5 6 7 8 |
def isEqual(x): return len(set(x)) <= 1 if __name__ == '__main__': x = [1, 1, 1, 1] print(isEqual(x)) # True |
2. Using count() function
Another option is to get a count of any arbitrary member of the list. If the count is the same as the length of the list, you can say that all the list elements are equal. Note this function will fail with an empty list.
|
1 2 3 4 5 6 7 8 |
def isEqual(x): return x.count(x[0]) == len(x) if __name__ == '__main__': x = [1, 1, 1, 1] print(isEqual(x)) # True |
3. Using all() function
Another plausible way is to use the all() function, which returns True if all elements of the iterable are true. This can be used as follows:
|
1 2 3 4 5 6 7 8 |
def isEqual(x): return all(i == x[0] for i in x) if __name__ == '__main__': x = [1, 1, 1, 1] print(isEqual(x)) # True |
4. Using slicing
Here’s a tricky solution using slicing:
|
1 2 3 4 5 6 7 8 |
def isEqual(x): return x[1:] == x[:-1] if __name__ == '__main__': x = [1, 1, 1, 1] print(isEqual(x)) # True |
5. Using NumPy
Numpy also offers the all() function, which can be used with the diff() function, as shown below:
|
1 2 3 4 5 6 7 8 9 10 |
import numpy as np def isEqual(x): return np.all(np.diff(x) == 0) if __name__ == '__main__': x = [1, 1, 1, 1] print(isEqual(x)) # True |
You can also use the allclose() function to check if all elements in the list equal to the first element.
|
1 2 3 4 5 6 7 8 9 10 |
import numpy as np def isEqual(x): return np.allclose(x, x[0]) if __name__ == '__main__': x = [1, 1, 1, 1] print(isEqual(x)) # True |
That’s all about determining whether all items in a list are identical in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)