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

What do you want to Learn Today?

  • Programming
    • C/C++
    • Python
    • Java
    • HTML CSS
    • SQL
  • CSE Subject
    • Compiler Design
    • Computer Network
    • COA
    • Data Structure
    • DBMS
    • Operating System
    • Theory of Automata
    • Web Technology
  • Linux
  • Trend
    • Artificial Intelligence (AI)
    • Big Data
    • Cloud Computing
    • Machine Learning (ML)
  • GATE CSE 2020
    • Self Study Plan
    • Complete Syllabus
    • FREE Test Series
    • Topper Interview (AIR 15)
    • Recommended Books by Topper
  • Career
    • Placement Interview
    • Jobs
    • Aptitude
    • Quiz
  • Material
    • Recommended Books
    • Software Installation
  • Contribute to Us
    • Write for Us
    • Submit Source Code or Program
    • Share Interview Experience
  • Tools

3 Ways to Check if all Elements in List are Same [Python Code]

Aniruddha Chaudhari/08 Oct, 17/39162/8
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 structure 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 reason to be in love with Python.

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

So, here you go to write the same program with simple logic in python.

Method 1: Using Python set:

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

When you find the set of the list, it removes all the duplicate elements.

Here is simple code with that you can check if all the elements of the list are same.

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"

If the length of the set is one, all the elements in the given list are same. Otherwise, not.

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.

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

If the total count of occurrences of any element (first element as per above code) in the list is 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"

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:

  • 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 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 set() function (method 1) is pretty easy and easily understood.

If you think, we can check if all elements in list are same, even by 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!

Pythonpython list

Related Posts

CodePython

Main Difference Between remove del and pop in Python List

C / C++CodeJAVAPython

[Explained in Detail] if else nested Programming Example in C, Java and Python

CodePythonSoftware Installation

How to Install and Run Jupyter Python Notebook [Complete Guide with Example]

Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold 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 Portal.

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!

Leave a Reply Cancel reply

Interview Experiences

AccentureAgriChain Akamai Amazon Amdocs American Express Attra Infotech BARC Barclays BlockGrain BYJUS Cisco Cognizant Coupon Dunia Credit Suisse DE Shaw Druva Experis IT Eze Software Factset Fiorano General Electric Incture Technologies Infosys Kasmo Cloud Microsoft MindTree Mu Sigma Numerify Opteamix Oracle Persistent Pole to Win Qualcomm Reliance Riverbed Syntel TCS Tech Mahindra Teradata Terralogic Virtusa Wipro

Interview Questions



You can share your interview experience.

Don’t Miss !

Latest Articles

Cisco Online Test Pattern and Interview Questions for Freshers


[7 Best Tips] How to Make Daily Study Timetable and Stick to It?


Persistent Written Test and Technical Coding Questions [Paper Pattern]


10 Top Website Design Tips for Small Business to Boost Up Your Sales


Main Difference Between remove del and pop in Python List


Tech Mahindra Placement (Online Test | Essay Writing | Interview Questions)


Importance of Career Exploration for High-School Students | Why?


Favorite Topic

AI algorithm array bigdata bit manipulation career Code Computer Network cpp data analytics database data scientist Data Structure db DBMS difference between Django education GATE GATE Topper Interview HTML ibm IBM ISDL interview IP address Java JavaScript Jobs Linked List linux linux cmd nit OOPs Concept os Programming Python python list Qualcomm SOAP sorting stack string vim webbrowser web development

Contribution to Community

  • Contribute to CSEstack Portal
  • Submit Your Source Code or Program
  • Share Your Interview Experience
  • CSEStack Leadership Board
  • Campus Ambassador Program by CSEstack

About CSEstack Portal

  • About CSEStack:
  • Contact Us
  • CSEStack Campus Ambassador
  • Recommended Books by Expert

© 2019 – CSEstack.org. All Rights Reserved.

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