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:
Python - Test if string contains element from list
Next article icon

Python – Test if tuple list has Single element

Last Updated : 10 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Tuple list, check if it is composed of only one element, used multiple times.

Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] 
Output : True 
Explanation : All elements are equal to 3.

Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] 
Output : False 
Explanation : All elements are not equal to any particular element. 

Method #1: Using loop

In this, we check for all the elements and compare them with the initial element of the initial tuple in the tuple list, if any element is different, the result is flagged off.

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
# Using loop
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking for similar elements in list
res = True
for sub in test_list:
    flag = True
    for ele in sub:
 
        # checking for element to be equal to initial element
        if ele != test_list[0][0]:
            flag = False
            break
    if not flag:
        res = False
        break
 
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Are all elements equal : True

Time complexity: O(n^2) where n is the number of sublists in the main list. The nested loop causes the time complexity to become quadratic. 
Auxiliary space: O(1) as the code only uses a few variables and does not allocate any additional memory dynamically.

Method #2 : Using all() + list comprehension

In this, we perform task of checking all elements to be same using all(), list comprehension is used to perform task of iterating through all the tuples in the tuple list.

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
# Using all() + list comprehension
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking for single element using list comprehension
res = all([all(ele == test_list[0][0] for ele in sub) for sub in test_list])
 
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Are all elements equal : True

Time Complexity: O(n^2), where n is the number of sublists in the tuple list.
Auxiliary Space: O(1), as no extra space is required.

Method #3: Using len() and count()

In this we will initialize an empty list and iterate over list of tuples and add each element of tuple to empty list.If count of first element is equal to length of list,  then all elements are same

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
x = []
res = False
for i in test_list:
    for j in i:
        x.append(j)
print()
if(x.count(x[0]) == len(x)):
    res = True
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]  Are all elements equal : True

Time Complexity: O(n^2), where n is the number of sublists in the tuple list.
Auxiliary Space: O(n), as extra space is required of size n.

Method #4 : Using extend() and count() methods

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 5), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
x = []
res = False
for i in test_list:
    x.extend(list(i))
if(x.count(x[0]) == len(x)):
    res = True
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 5), (3, 3)] Are all elements equal : False

Method #5 : Using extend() and operator.countOf() methods

Approach

  1.  Initiated a for loop to traverse over the list of tuples
  2. Convert each tuple element to list
  3. And extend all list to a new list
  4.  Now check the count of first element in the list is equal to the length of list
  5.  If equal assign True to res
  6.  Display res

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 5), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
x = []
res = False
for i in test_list:
    x.extend(list(i))
import operator
if(operator.countOf(x,x[0]) == len(x)):
    res = True
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 5), (3, 3)] Are all elements equal : False

Time Complexity : O(N)

Auxiliary Space : O(1)

Method #5 : Using extend()+len()+* operator

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 5), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
x = []
res = False
for i in test_list:
    x.extend(list(i))
a = [x[0]]*len(x)
if(a == x):
    res = True
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 5), (3, 3)] Are all elements equal : False

Method #5 : Using set()+len() methods

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
x = []
res = False
for i in test_list:
    for j in i:
        x.append(j)
print()
if(len(set(x)) == 1):
    res = True
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]  Are all elements equal : True

Method #6: Using filter()+list()+ lambda functions

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
K = test_list[0][0]
# Check if tuple list has all single element
# Using loop
res = True
for tup in test_list:
    res = len(list(filter(lambda x: x != K, tup))) == 0
    if(not res):
        break
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Are all elements equal : True

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)

Method #7: Using recursion method.

Python3




# Python3 code to demonstrate working of
# Test if tuple list has Single element
 
#defining recursive function
def is_single(start,lst,value):
  if start==len(lst):  #base condition
    return True
  if not all(map(lambda x:x==value,lst[start])):
         return False
  return is_single(start+1,lst,value)  #calling recursive method
# initializing list
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
 
# printing original list
print("The original list is : " + str(test_list))
K = test_list[0][0]
# Check if tuple list has all single element
 
res=is_single(0,test_list,K)
# printing result
print("Are all elements equal : " + str(res))
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Are all elements equal : True

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)

Method #8: Using the itertools.groupby() function

Python3




import itertools
test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)]
# printing original list
print("The original list is : " + str(test_list))
res = all(len(list(group)) == 1 for key, group in itertools.groupby(test_list, lambda x: len(x)))
print("Are all elements single : " + str(res))
#This code is contributed by Vinay Pinjala.
 
 
Output
The original list is : [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Are all elements single : True

Time Complexity: O(N*N)
Auxiliary Space: O(N*N)



Next Article
Python - Test if string contains element from list
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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
  • Python - Test if string contains element from list
    Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string. Using any() with a generator expressionany() is the most efficient way to check if any element from the list is present in the list. [GFGTABS] Python s = "Pyth
    3 min read
  • Python - Test if any set element exists in List
    Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1},
    4 min read
  • Python - Count elements in tuple list
    Sometimes, while working with data in form of records, we can have a problem in which we need to find the count of all the records received. This is a very common application that can occur in Data Science domain. Let’s discuss certain ways in which this task can be performed. Method #1: Using len()
    5 min read
  • Python - Test if Tuple contains K
    Sometimes, while working with Python, we can have a problem in which we have a record and we need to check if it contains K. This kind of problem is common in data preprocessing steps. Let’s discuss certain ways in which this task can be performed. Method #1: Using any() + map() + lambda Combination
    6 min read
  • Python | Test if tuple is distinct
    Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is a brute force
    4 min read
  • Python - Check if tuple list has all K
    Sometimes, while working with Python records, we can have a problem in which we need to test if all the elements in tuples of tuple list are K. This problem can have applications in many data domains such as Machine Learning and Web development. Let's discuss certain ways in which this task can be p
    7 min read
  • Python - Test if greater than preceding element in Tuple List
    Given list of tuples, check if preceding element is smaller than the current element for each element in Tuple list. Input : test_list = [(5, 1), (4, 9), (3, 5)] Output : [[False, False], [False, True], [False, True]] Explanation : First element always being False, Next element is checked for greate
    9 min read
  • Python - Extract tuple supersets from List
    Sometimes, while working with Python tuples, we can have a problem in which we need to extract all the tuples, which have all the elements in target tuple. This problem can have application in domains such as web development. Let's discuss certain way in which this problem can be solved. Input : tes
    5 min read
  • Python | Test if any list element returns true for condition
    Sometimes, while coding in Python, we can have a problem in which we need to filter a list on basis of condition met by any of the element. This can have it's application in web development domain. Let's discuss a shorthand in which this task can be performed. Method : Using any() + list comprehensi
    4 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