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 - Extracting Priority Elements in Tuple List
Next article icon

Python – Test if greater than preceding element in Tuple List

Last Updated : 18 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 greater value. 

Input : test_list = [(1, 8), (2, 2), (3, 6), (4, 2)] 
Output : [[False, True], [False, False], [False, True], [False, False]] 
Explanation : 8 and 6 are greater cases in above cases, hence True.

Method #1 : Using list comprehension + enumerate() The combination of above functions can be used to solve this problem. In this, we perform the task of checking for greater value using one liner list comprehension and enumerate() is used to work with indices while nested iteration. 

Python3




# Python3 code to demonstrate working of
# Test if greater than preceding element in Tuple List
# Using list comprehension + enumerate()
 
# initializing list
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Test if greater than preceding element in Tuple List
# Indices checked using enumerate() and True and false
# values assigned in list comprehension
res = [[True if idx > 0 and j > i[idx - 1] else False
        for idx, j in enumerate(i)] for i in test_list]
 
# printing result
print("Filtered values : " + str(res))
 
 
Output : 
The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [[False, True, False], [False, False, True], [False, True, True]]

Time complexity: O(n^2), where n is the length of the longest tuple in the list. This is because the program iterates through each element of each tuple in the list using nested loops, and the length of the inner loop depends on the length of the longest tuple.
Auxiliary space: O(n^2), as it creates a new 2-dimensional list of the same size as the input list to store the boolean values for each element in each tuple.

Method #2 : Using tee() + zip() + list comprehension This is one of the ways in which this task can be performed. In this, we extract elements and render them in tuple of size = 2, using tee(). List comprehension and zip() are used to construct the desired result. 

Python3




# Python3 code to demonstrate working of
# Test if greater than preceding element in Tuple List
# Using tee() + zip() + list comprehension
from itertools import tee
 
# helper function
def pair(test_list):
     
    # pairing elements in 2 sized tuple
    x, y = tee(test_list)
    next(y, None)
    return zip(x, y)
 
# initializing list
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Test if greater than preceding element in Tuple List
# Using tee() + zip() + list comprehension
res = []
for sub in test_list:
     
    # appending result by checking with Dual Pairs
    res.append(tuple((False, )) + tuple([x < y for x, y in pair(sub)]))
     
# printing result
print("Filtered values : " + str(res))
 
 
Output : 
The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [[False, True, False], [False, False, True], [False, True, True]]

Time complexity: O(nm), where n is the length of the input list and m is the length of each tuple in the input list.
Auxiliary space: O(nm), where n is the length of the input list and m is the length of each tuple in the input list. 

Method#3: Using a for loop and if-else statement

Python3




# initializing list
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
 
# printing original list
print("The original list : " + str(test_list))
 
# using for loop and if-else statement
res = []
for i in test_list:
    sub_list = []
    for idx, j in enumerate(i):
        if idx > 0 and j > i[idx - 1]:
            sub_list.append(True)
        else:
            sub_list.append(False)
    res.append(sub_list)
 
# printing result
print("Filtered values : " + str(res))
#This code is contributed by Vinay Pinjala.
 
 
Output
The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [[False, True, False], [False, False, True], [False, True, True]]

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

Method #4: Using map() + lambda function

You can use the map() function along with a lambda function to apply the same logic used in the for loop and if-else statement in a more concise way:

Python3




# initializing list
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
 
# printing original list
print("The original list : " + str(test_list))
 
# using map() and lambda function
res = list(map(lambda x: [x[idx] > x[idx-1] if idx > 0 else False for idx in range(len(x))], test_list))
 
# printing result
print("Filtered values : " + str(res))
 
 
Output
The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [[False, True, False], [False, False, True], [False, True, True]]

Time complexity: O(n*m), where n is the number of tuples in the test_list, and m is the maximum number of elements in a tuple. 

Auxiliary space: O(nm), where n is the number of tuples in the test_list, and m is the maximum number of elements in a tuple. 

Method #5: Using a generator expression

In this approach, the generator expression (j > i[idx – 1] for idx, j in enumerate(i) if idx > 0) generates a boolean value for each element in the tuple, indicating whether it is greater than the preceding element. The all() function is used to check if all these boolean values are true for a given tuple, and the result is stored in a list comprehension.

Python3




# Python3 code to demonstrate working of
# Test if greater than preceding element in Tuple List
# Using generator expression and all()
 
# initializing list
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
 
# printing original list
print("The original list : " + str(test_list))
 
# Test if greater than preceding element in Tuple List
# Using generator expression and all()
res = [all(j > i[idx - 1] for idx, j in enumerate(i) if idx > 0)
       for i in test_list]
 
# printing result
print("Filtered values : " + str(res))
 
 
Output
The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [False, False, True]

Time complexity: O(nm), where n is the length of the input list and m is the length of the tuples in the input list
Auxiliary space: O(n), as it creates a new list res with a length equal to the number of tuples in the input list. 

Method #6: Using numpy:

Algorithm:

  1. Convert the given list of tuples to a NumPy array.
  2. Create a boolean NumPy array of the same shape as the input array, with all elements initialized to False.
  3. Compare each element in each row of the input array with its preceding element, using NumPy’s element-wise comparison.
  4. Replace the first element in each row of the resulting boolean array with False, since there is no preceding element for the first element in each row.
  5. Return the resulting boolean array as a list of lists.

Python3




import numpy as np
 
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
# printing original list
print("The original list : " + str(test_list))
arr = np.array(test_list)
res = np.hstack((np.zeros((arr.shape[0], 1), dtype=bool), arr[:, 1:] > arr[:, :-1]))
print("Filtered values : " + str(res.tolist()))
#This code is contributed by Jyothi pinjala
 
 

Output:

The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [[False, True, False], [False, False, True], [False, True, True]]

Time Complexity:

Creating a NumPy array from a list takes O(n) time where n is the number of elements in the list.
Comparing each element in each row of the input array with its preceding element using NumPy’s element-wise comparison takes O(m * n) time where m is the number of rows and n is the number of columns in the input array.

Replacing the first element in each row of the resulting boolean array with False takes O(m) time.
Converting the resulting boolean array to a list of lists takes O(m * n) time.
Therefore, the overall time complexity of the algorithm is O(m * n).

Auxiliary Space:

Creating a NumPy array from a list requires O(m * n) space, where m is the number of rows and n is the number of columns in the list of tuples.
Creating a boolean array of the same shape as the input array requires O(m * n) space.
Converting the boolean array to a list of lists requires O(m * n) space.
Therefore, the overall space complexity of the algorithm is O(m * n).

Method #7: Using pandas.DataFrame.diff()

  • Convert the list of tuples to a pandas DataFrame using pd.DataFrame().
  • Use the .diff() method with axis=1 to calculate the difference between each element in a row and the preceding element.
  • Use the .gt() method to check which elements are greater than their preceding element.
  • Convert the resulting DataFrame to a list of lists using .values.tolist().

Python3




import pandas as pd
 
# initializing list
test_list = [(3, 5, 1), (7, 4, 9), (1, 3, 5)]
 
# printing original list
print("The original list : " + str(test_list))
 
# convert list to DataFrame
df = pd.DataFrame(test_list)
 
# calculate difference between elements in each row
diff = df.diff(axis=1)
 
# check which elements are greater than their preceding element
res = diff.gt(0)
 
# convert DataFrame to list of lists
res = res.values.tolist()
 
# printing result
print("Filtered values : " + str(res))
 
 

Output-

The original list : [(3, 5, 1), (7, 4, 9), (1, 3, 5)] Filtered values : [[False, True, False], [False, False, True], [False, True, True]]

Time complexity: O(nm), where n is the number of rows and m is the number of elements in each row.
Space complexity: O(nm), for the pandas DataFrame and resulting list of lists.



Next Article
Python - Extracting Priority Elements in Tuple List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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 - Extracting Priority Elements in Tuple List
    Sometimes, while working with Python Records, we can have a problem in which we need to perform extraction of all the priority elements from records, which usually occur as one of the binary element tuple. This kind of problem can have possible application in web development and gaming domains. Let'
    5 min read
  • Python | Check if element is present in tuple of tuples
    Sometimes the data that we use is in the form of tuples and often we need to look into the nested tuples as well. The common problem that this can solve is looking for missing data or na value in data preprocessing. Let's discuss certain ways in which this can be performed. Method #1: Using any() an
    4 min read
  • Python - Test if tuple list has Single element
    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 elemen
    8 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 | Remove tuples from list of tuples if greater than n
    Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial lis
    6 min read
  • Python - Extract Preceding Record from list values
    Sometimes, while working with Tuple records, we can have a problem in which we need to extract the record, which is preceding to particular key provided. This kind of problem can have application in domains such as web development and day-day programming. Let's discuss certain ways in which this tas
    9 min read
  • Python | Filter tuples according to list element presence
    Sometimes, while working with records, we can have a problem in which we have to filter all the tuples from a list of tuples, which contains atleast one element from a list. This can have applications in many domains working with data. Let's discuss certain ways in which this task can be performed.
    8 min read
  • Python - Filter Tuples Product greater than K
    Given a Tuple list, extract all with product greater than K. Input : test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)], K = 50 Output : [(4, 5, 7), (8, 4, 2)] Explanation : 140 and 64 are greater than 50, hence tuples extracted.Input : test_list = [(4, 5, 7), (1, 2, 3), (8, 4, 2), (2, 3, 4)],
    7 min read
  • Python - Test if Values Sum is Greater than Keys Sum in dictionary
    Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, w
    8 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