Sometimes, while working with Tuple records, we can have a problem in which we need to extract the record, which is preceeding 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 task can be performed.
Input : test_list = [(‘Gfg’, 3), (‘is’, 4), (‘best’, 1), (‘for’, 10), (‘geeks’, 11)], key = ‘geeks’
Output : (‘for’, 10)
Input : test_list = [(‘Gfg’, 3), (‘is’, 4), (‘best’, 1), (‘for’, 10), (‘geeks’, 11)], key = ‘is’
Output : (‘Gfg’, 3)
Method #1 : Using
zip() + enumerate() + loop
The combination of above functions can be used to perform this particular task. In this, we create 2 lists, one with starting with next index. The zip(), helps to connect them and return the desired result using enumerate() for extracting index.
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)] The Preceeding record : ('best', 1)
Method #2 : Using list comprehension +
The combination of above functions can be used to solve this problem. In this, we perform the task of extracting the previous element to manually test previous key, rather than creating a separate list as in previous method.
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)] The Preceeding record : [('best', 1)]
- Python - Extract Dictionary values list to List
- Python - Extract Unique values dictionary values
- Python - Extract ith column values from jth column values
- Python - Extract values of Particular Key in Nested Values
- Python - Nested record values summation
- Python | Preceding element tuples in list
- Python - Test if greater than preceding element in Tuple List
- Python - Maximum value in record list as tuple attribute
- Python | Maximize Record list
- Python - List lengths as record attribute
- Python | Record elements Average in List
- Python | Column Average in Record List
- Python - Minimum in each record value list
- Python - Value Dictionary from Record List
- Ways to extract all dictionary values | Python
- Python | Extract filtered Dictionary Values
- Python - Extract target key from other key values
- Python - Extract Numerical Dictionary values
- Python - Extract selective keys' values Including Nested Keys
- Python - Assign values to Values List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.