When you think about this query, the first thing that comes to your mind is to run a loop and check if all elements in list are same.
Below is a simple program.
listChar = ['z','z','z','z'] nTemp = listChar[0] bEqual = True for item in listChar: if nTemp != item: bEqual = False break; if bEqual: print("All elements in list are equal.") else: print("All elements in list are not equal.")
This code runs fine. And there is nothing wrong with this logic as you write it in many other programming languages. But, this is not the way you write this code in Python.
The list is one of the very prominent data structures in Python. And there are really interesting pieces of stuff you can code with simple two or three lines of code. For me, this is one of the finest reasons to be in love with Python.
Let’s see how to write a Python program to check if all the elements in the list are equal.
Here you go to write the same program with simple logic in Python.
Set is a collection type in Python, just like list and tuple (Ref: the difference between list and tuple). The set is different as it can’t have duplicate elements, unlike list and tuple. All the elements in the set are unique.
So, the task is to find all the unique elements from the list. We can use the set to find all the unique elements from the list.
When you find the set of the list, it removes all the duplicate elements.
Algorithm:
Here is a simple code with which you can check if all the elements of the list are the same using the inbuilt set() method.
listChar = ['z','z','z','z'] if(len(set(listChar))==1): print("All elements in list are same.") else: print("All elements in list are not same.")
Output:
All elements in list are same.
Instead if set()
method, we can also use count()
method.
The count()
is the list object function which returns the number of occurrences of the input element.
To check if all elements in list are same, you can compare the number of occurrences of any elements in the list with the length of the list.
Algorithm:
listChar = ['z','z','z','z'] if listChar.count(listChar[0]) == len(listChar): print("All elements in list are same.") else: print("Elements in list are different.")
Output:
All elements in list are same.
If the total count of occurrences of an element (first element as per the above code) in the list is the same as the length of the list, all the elements in the list are equal. Otherwise, elements in the list are different.
The all() is a function that takes the iterable as an input and returns true if all the elements of the iterable are true. Otherwise, false.
The simple solution to our problem is – to check if all elements in list are same as the first element in the list.
listChar = ['z','z','z','z'] if all(x == listChar[0] for x in listChar): print("All elements in list are equal.") else: print("All elements in list are not equal.")
Output:
All elements in list are same.
If all() function returns true means all the elements in the list are equal. Otherwise, not equal.
Note: If you are comparing two elements in Python, remember- comparing using ‘is’ and ‘==’ is different.
Some other tricky questions in Python, you can try:
This is all about this post. I am sure, you find some valuable solutions to your problem. If you ask me to choose one solution, using the set() function (method 1) is pretty easy and easily understood.
If you think, we can check if all elements in list are same, even in a better way, write in a comment below. I would love that.
If you are interested in learning Python, don’t miss to read our complete Python tutorial.
Happy Pythoning!
In the if statement using set, why enclose the len function in parens?
if(len(set(listChar))==1):
It seems to work without it, just curious about this syntax.
Thanks for tips!
Hey Matthew, yeah!
It works without parenthesis as well. Enclosing condition with parenthesis inside if statement is not mandatory. It is all about how we do find it comfortable.
There may be no difference in code length or clarity but there is a big difference in speed:
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]
Type ‘copyright’, ‘credits’ or ‘license’ for more information
IPython 6.1.0 — An enhanced Interactive Python. Type ‘?’ for help.
In [1]: L = [‘z’] * 4096
In [2]: %timeit len(set(L)) == 1
38.9 µs ± 207 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [3]: %timeit L.count(L[0]) == len(L)
19 µs ± 3.96 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [4]: %timeit all(x == L[0] for x in L)
365 µs ± 1.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Agree!
If the programmer is more concerned executing code faster, s/he needs to choose one which runs faster.
Code snippets in this article are to brainstorm the different ways of doing the same thing and exploring different Python tactics.
Thanks for clarifying and putting your thought!
Apart from the set solution, none of the proposed solution are stable with respect to null lists. An appropriate test should be added.
Yeah, You are right!
Code snippet shared in this post are written in consideration of – at least one element in the list.
For a null list, an appropriate check is needed to add by the programmer.
Another pythonic (and fast) solution is using fromkeys method of dictionary:
This is really interesting and tiny code.
Thanks for sharing!
I was looking for the same solution. Thanks for this article and explaining this simple Python list trick.
You’re welcome, Juliane!
I saw your Python tutorials. You have almost covered all the topics. I find your tutorials very easy to learn. Thanks, Aniruddha!
You’re welcome, Vallie! Very glad you like my tutorials.
# Printing an expense code
expense_list = [2340, 2500, 2100, 3100, 2980]
months = [‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’, ‘May’]
total = 0
for i in range(len(expense_list)):
print(‘Month:’, months[i], ‘Expense:’, expense_list[i])
total = total + expense_list[i]
exp = input(‘Enter expense amount: ‘)
if exp == expense_list:
print(‘Congratulations!! Your amount is in the list…;)’, exp)
break
else:
print(‘Sorry!! Your entered amount is not found…:(‘, exp)
Hai bro!! Is the above code correct for inserting the expenses…
actually am not getting how to insert expenses. If we insert if its equals to expenses-list it should show congrats comment
if its not it should show sorry statement,,,
could you please help me out.
Thank you
Hi Arun,
Looks like you want to check the user entered expenses is in the expense_list or not.
You can not do this by “if exp == expense_list:”, instead use “if exp in expense_list:”.
This is a list membership test.
Hello, I was wondering if you could help me write a function that checks if all the elements of a list are the same by using selection sort or bubble sort in python. Thank you in advance