• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[3 Methods] Check if all Elements in List are Same in Python

Aniruddha Chaudhari/275364/16
CodePython

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 absolutely 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.

Lets see how to write a Python program to check if all the elements in the list are equal.

How to Check if all Elements in List are same in Python?

Here you go to write the same program with simple logic in python.

Method 1: Using Set()

Set is a collection type in Python, just like list and tuple (Ref: the difference between list and tuple). 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:

  • Cobert the given list into the set.
  • If the length of the set is one, all elements in the list are the same. Else, elements in the list are different.

Here is a simple code with that you can check if all the elements of the list are 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.

Method 2: Using Python count() Function

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:

  • Count the number of occurrences of first elements in the list (says ‘x’).
  • Count the length of the list (says ‘y’).
  • If the ‘x’ is equal to ‘y’, all the elements in the list are the same. Otherwise, not.
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 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.

Method 3: Using Python 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.

The simple solution to our problem is – 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 give a try:

  • Compare if two lists are the same.
  • Randomly Select Item from List in Python (choice() method)
  • Get all the Permutations of String
  • Remove all 0 from a dictionary in Python
  • Find the longest line from a file in Python Program

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 the 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!

Python Interview Questions eBook

Pythonpython list
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Matthew
    October 9, 2017 at 3:19 pm

    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!

    • Reply
      Aniruddha Chaudhari
      October 9, 2017 at 4:28 pm

      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.

  • Reply
    Gadget Steve
    October 11, 2017 at 5:44 am

    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)

    • Reply
      Aniruddha Chaudhari
      October 11, 2017 at 3:32 pm

      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!

  • Reply
    Ruud
    October 11, 2017 at 6:01 am

    Apart from the set solution, none of the proposed solution are stable with respect to null lists. An appropriate test should be added.

    • Reply
      Aniruddha Chaudhari
      October 11, 2017 at 3:26 pm

      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.

  • Reply
    Glauco
    October 11, 2017 at 7:52 am

    Another pythonic (and fast) solution is using fromkeys method of dictionary:

    len(dict.fromkeys(listChar)) == 1
    • Reply
      Aniruddha Chaudhari
      October 11, 2017 at 3:22 pm

      This is really interesting and tiny code.

      Thanks for sharing!

  • Reply
    Juliane
    July 22, 2019 at 10:48 pm

    I was looking for the same solution. Thanks for this article and explaining this simple Python list trick.

    • Reply
      Aniruddha Chaudhari
      July 23, 2019 at 12:25 pm

      You’re welcome, Juliane!

  • Reply
    Vallie
    August 1, 2019 at 9:07 am

    I saw your Python tutorials. You have almost covered all the topics. I find your tutorials very easy to learn. Thanks, Aniruddha!

    • Reply
      Aniruddha Chaudhari
      August 1, 2019 at 9:50 am

      You’re welcome, Vallie! Very glad you like my tutorials.

  • Reply
    Arun
    September 3, 2019 at 5:33 pm

    # 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)

  • Reply
    Arun
    September 3, 2019 at 5:36 pm

    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

    • Reply
      Aniruddha Chaudhari
      September 3, 2019 at 7:04 pm

      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.

  • Reply
    Majki
    May 26, 2020 at 4:03 am

    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

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard