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 - Flatten Nested Tuples
Next article icon

Python – Ordered tuples extraction

Last Updated : 17 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a tuple list, get all the tuples which are sorted in ascending order.

Input : test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (2, 5, 6), (9, 1)] 
Output : [(3, 4, 6), (2, 5, 6)] 
Explanation : Sorted tuples are extracted. 

Input : test_list = [(5, 4, 6, 2, 4), (3, 4, 1), (2, 5, 4), (9, 1)] 
Output : [] 
Explanation : No Sorted tuples.

Method #1 : Using list comprehension + sorted()

In this, we check if tuple is ordered using sorted(), and list comprehension is used to iterate for each tuple.

Python3




# Python3 code to demonstrate working of
# Ordered tuples extraction
# Using list comprehension + sorted()
 
# initializing list
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorted() used to order, comparison operator to test
res = [sub for sub in test_list if tuple(sorted(sub)) == sub]
 
# printing result
print("Ordered Tuples : " + str(res))
 
 
Output
The original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)] Ordered Tuples : [(3, 4, 6), (9, 10, 34), (2, 5, 6)]

Time Complexity: O(nlogn), where n is the length of the input list. 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”. 

Method #2 : Using filter() + lambda + sorted()

In this, the task of filtering is done using filter(), sorted() fed to lambda for with comparison to get required result.

Python3




# Python3 code to demonstrate working of
# Ordered tuples extraction
# Using filter() + lambda + sorted()
 
# initializing list
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorted() used to order, comparison operator to test
res = list(filter(lambda sub: tuple(sorted(sub)) == sub, test_list))
 
# printing result
print("Ordered Tuples : " + str(res))
 
 
Output
The original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)] Ordered Tuples : [(3, 4, 6), (9, 10, 34), (2, 5, 6)]

Method#3: Using Recursive method.

Python3




def ordered_tuples(test_list, result=[]):
    if len(test_list) == 0:
        return result
    else:
        first, *rest = test_list
        if tuple(sorted(first)) == first:
            result.append(first)
        return ordered_tuples(rest, result)
 
# initializing list
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# calling function to extract ordered tuples
res = ordered_tuples(test_list)
 
# printing result
print("Ordered Tuples : " + str(res))
#this code contributed by tvsk
 
 
Output
The original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)] Ordered Tuples : [(3, 4, 6), (9, 10, 34), (2, 5, 6)]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using all()

Step-by-step approach:

  • Traverse through each character in the string.
  • For each character, check if it is an opening parenthesis or closing parenthesis. If it is an opening parenthesis, push it to the stack. If it is a closing parenthesis, check if the stack is empty or the top of the stack is not the corresponding opening parenthesis for the closing parenthesis. If it is, return False.
  • After traversing through the string, check if the stack is empty. If it is, return True. If it is not, return False.

Below is the implementation of the above approach:

Python3




test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
 
# printing original list
print("The original list is : " + str(test_list))
# Using all() to filter ordered tuples
ordered_tuples = list(filter(lambda tup: all(tup[i] <= tup[i+1] for i in range(len(tup)-1)), test_list))
 
# Print the result
print("Ordered Tuples: ", ordered_tuples)
#This code is contributed by Vinay Pinjala.
 
 
Output
The original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)] Ordered Tuples:  [(3, 4, 6), (9, 10, 34), (2, 5, 6)]

Time complexity: The time complexity of this approach is O(n), where n is the length of the input string. This is because we need to traverse through each character in the string once.
Auxiliary space: The auxiliary space complexity of this approach is O(n), where n is the length of the input string. This is because we need to store the opening parenthesis in the stack and the maximum size of the stack is equal to the length of the input string.

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

Algorithm:

1.Import itertools module
2.Initialize an empty list ordered_tuples to store ordered tuples
3.Iterate over the groups returned by itertools.groupby() method, grouped based on whether each tuple satisfies the ordering condition
4.If a group contains only ordered tuples, extend the ordered_tuples list with the tuples in the group
5.Print the ordered_tuples list

Python3




import itertools
 
test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
# printing original list
print("The original list is : " + str(test_list))
  
 
ordered_tuples = []
for k, g in itertools.groupby(test_list, lambda tup: all(tup[i] <= tup[i+1] for i in range(len(tup)-1))):
    if k:
        ordered_tuples.extend(g)
 
print("Ordered Tuples: ", ordered_tuples)
 
#This code is contributed by Jyothi pinjala.
 
 
Output
The original list is : [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)] Ordered Tuples:  [(3, 4, 6), (9, 10, 34), (2, 5, 6)]

Time complexity: O(nlogn) where n is the total number of elements in all tuples. This is because the itertools.groupby() method and the all() function take O(n) time complexity, while the extend() method takes O(m) time complexity, where m is the number of elements in the group of ordered tuples. The total time complexity is dominated by the sorting that happens inside itertools.groupby(), which has a time complexity of O(nlogn).

Auxiliary Space: O(m) where m is the number of elements in the largest group of ordered tuples. This is because the itertools.groupby() method groups the input list into separate sublists, and the largest sublist needs to be stored in memory.

Method #6: Using map() and set()

Step-by-step approach:

  1. Define a list of tuples named “test_list” containing multiple tuples with different number of integers in each tuple.
  2. Create an empty list named “res”.
  3. Iterate through each tuple “tup” in the “test_list”.
  4. For each “tup”, sort the integers using “sorted” function and convert the sorted integers into tuple using “tuple” function. Then, map the tuple of sorted integers to “map” function.
  5. Then, convert the output of “map” function to set using “set” function.
  6. Check if the set obtained in the previous step is equal to the set containing the original tuple “tup” using “==” operator.
  7. If the sets are equal, then the tuple “tup” is ordered. Append it to the list “res”.
  8. After iterating through all tuples in the “test_list”, print the list “res” containing all ordered tuples.

Below is the implementation of the above approach:

Python3




test_list = [(5, 4, 6, 2, 4), (3, 4, 6), (9, 10, 34), (2, 5, 6), (9, 1)]
res = []
 
for tup in test_list:
    if set(map(tuple, map(sorted, [tup]))) == {tup}:
        res.append(tup)
 
print("Ordered Tuples: ", res)
 
 
Output
Ordered Tuples:  [(3, 4, 6), (9, 10, 34), (2, 5, 6)]

Time complexity: O(nklog k)
Auxiliary space: O(n*k)



Next Article
Python - Flatten Nested Tuples
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Addition in Nested Tuples - Python
    Sometimes, while working with records, we can have a problem in which we require to perform index wise addition of tuple elements. This can get complicated with tuple elements to be tuple and inner elements again be tuple. Let's discuss certain ways in which this problem can be solved. Method #1: Us
    6 min read
  • Python - Order Tuples by List
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform ordering of all the tuples keys using external list. This problem can have application in data domains such as Data Science. Let's discuss certain ways in which this task can be performed. Input : test_lis
    7 min read
  • Python - Flatten Nested Tuples
    Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let's discuss certain way in which this task can be performe
    7 min read
  • Create Dictionary Of Tuples - Python
    The task of creating a dictionary of tuples in Python involves mapping each key to a tuple of values, enabling structured data storage and quick lookups. For example, given a list of names like ["Bobby", "Ojaswi"] and their corresponding favorite foods as tuples [("chapathi", "roti"), ("Paraota", "I
    3 min read
  • Python - Extend consecutive tuples
    Given list of tuples, join consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Output : [(3, 5, 6, 7, 3, 2, 4, 3), (3, 2, 4, 3, 9, 4), (9, 4, 2, 3, 2)] Explanation : Elements joined with their consecutive tuples. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3)] Ou
    3 min read
  • Python | Tuple XOR operation
    Sometimes, while working with records, we can have a problem in which we may need to perform mathematical bitwise XOR operation across tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed. Method #1: Using zip() + generator expression
    6 min read
  • Python | Compare tuples
    Sometimes, while working with records, we can have a problem in which we need to check if each element of one tuple is greater/smaller than it's corresponding index in other tuple. This can have many possible applications. Let's discuss certain ways in which this task can be performed. Method #1 : U
    4 min read
  • Python Tuple - index() Method
    While working with tuples many times we need to access elements at a certain index but for that, we need to know where exactly is that element, and here comes the use of the index() function. In this article, we will learn about the index() function used for tuples in Python. Example : The Index() m
    3 min read
  • Python - Extract Symmetric Tuples
    Sometimes while working with Python tuples, we can have a problem in which we need to extract all the pairs which are symmetric, i.e for any (x, y), we have (y, x) pair present. This kind of problem can have application in domains such as day-day programming and web development. Let's discuss certai
    4 min read
  • Python - Pairwise Addition in Tuples
    Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element addition. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + ge
    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