Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if any element in list satisfies a condition-Python
Next article icon

Python – Check if all elements in List are same

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To check if all items in list are same, we have multiple methods available in Python.

Using Set

Using set() is the best method to check if all items are same in list.

Python
a = [3, 3, 3, 3]  # Check if all elements are the same result = len(set(a)) == 1 print(result) 

Output
True 

Explanation:

  • Converting given list to set will take O(n) time, because we are adding each item in set.
  • In Set, checking length can be done in O(1) constant time.

Let’s explore some other methods and see how we can check if all elements in a list are same or not.

Table of Content

  • Using all() method
  • Using count() method
  • Using For Loop
  • Using List Slicing

Using all() method

all() function checks if all elements in an iterable meet a condition. By comparing each element to the first list we can confirm if the entire list is uniform.

Python
#Driver Code Starts{ a = [5, 5, 5, 5]  #Driver Code Ends }  # Check if all elements are the same result = all(x == a[0] for x in a)  #Driver Code Starts{ print(result)  #Driver Code Ends } 

Output
True 

Using all() method can be preferred, as it stops iterating once it finds any mismatched item during comparison.

Explanation:

  • x == a[0] for x in a : For each iteration, it checks if the current element x is equal to the first element of the list (a[0] which is 5 in this case)
  • all() function takes above generator and checks if all values evaluates to True.

Using count() method

count() method will iterate over the entire list to count the occurrence of first item.

Python
a = [5, 5, 5, 5]  # count the occurence of first element res = a.count(a[0]) == len(a)  print(res) 

Output
True 

Explanation:

  • a.count(a[0]) counts how many times the first element appears in the list.
  • this result is compared with length of list using len(a)
  • If both are same, above code will return True, else False.

Using For Loop

A simple loop iterates through the list and checks if all elements are equal to the first element. This approach is easy to understand and implement.

Python
a = [1, 1, 1, 1]  # Check if all elements are the same result = True  for x in a:     if x != a[0]:         result = False         break  print( result) 

Output
True 

Explanation:

  • The loop compares each element to the first.
  • If a mismatch is found the result is set to False and the loop exits

Using List Slicing

This approach compares all elements in the list to the first element using slicing. It’s concise and effective for short lists and comparing these ensures uniformity.

Python
#Driver Code Starts{ a = [2, 2, 2, 2]  #Driver Code Ends }  # Check if all elements are the same result = a[1:] == a[:-1]  #Driver Code Starts{ print(result)  #Driver Code Ends } 

Output
True 

Explanation:

  • a[1:] contains all elements except the first.
  • a[:-1] contains all elements except the last.
  • If a[1:] and a[:-1] are same, it means all elements in the original list are the same.

Note: We should avoid using this method if the list could be empty or contain only one element, as it may give misleading results.




Next Article
Check if any element in list satisfies a condition-Python

S

Shivam_k
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python | Check if all elements in a list are identical
    Given a list, write a Python program to check if all the elements in that list are identical using Python. Examples: Input : ['a', 'b', 'c'] Output : False Input : [1, 1, 1, 1] Output : TrueCheck if all elements in a list are identical or not using a loop Start a Python for loop and check if the fir
    5 min read
  • Python - Test if all elements in list are of same type
    When working with lists in Python, there are times when we need to ensure that all the elements in the list are of the same type or not. This is particularly useful in tasks like data analysis where uniformity is required for calculations. In this article, we will check several methods to perform th
    3 min read
  • Test if all elements are present in list-Python
    The task of testing if all elements are present in a list in Python involves checking whether every item in a target list exists within a reference list. For example, given two lists a = [6, 4, 8, 9, 10] and b = [4, 6, 9], the task is to confirm that all elements in list b are also found in list a.
    3 min read
  • Python - Check if Kth index elements are unique
    Given a String list, check if all Kth index elements are unique. Input : test_list = ["gfg", "best", "for", "geeks"], K = 1 Output : False Explanation : e occurs as 1st index in both best and geeks.Input : test_list = ["gfg", "best", "geeks"], K = 2 Output : True Explanation : g, s, e, all are uniqu
    5 min read
  • Check if any element in list satisfies a condition-Python
    The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio
    3 min read
  • Python - Check if List contains elements in Range
    Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range. Using any() Function
    3 min read
  • Python - Check if element is present in tuple
    We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True. Using in Operatorin operator checks if an element is present in a tuple by
    2 min read
  • Python | Check if tuple and list are identical
    Sometimes while working with different data in Python, we can have a problem of having data in different containers. In this situations, there can be need to test if data is identical cross containers. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is the
    7 min read
  • Python - Check if any list element is present in Tuple
    Given a tuple, check if any list element is present in it. Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] Output : True Explanation : 10 occurs in both tuple and list. Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] Output : False Explanation : No common elements.
    6 min read
  • Python | Check if all elements in list follow a condition
    Sometimes, while working with Python list, we can have a problem in which we need to check if all the elements in list abide to a particular condition. This can have application in filtering in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences