Python - Extract Preceding Record from list values
Last Updated :
26 Apr, 2023
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 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.
Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# Using zip() + enumerate() + loop
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
key = 'for'
# Extract Preceding Record
# Using zip() + enumerate() + loop
for idx, (a, b) in enumerate(zip(test_list, test_list[1:])):
if b[0] == key:
res = (a[0], a[1])
# printing result
print("The Preceding record : " + str(res))
OutputThe original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : ('best', 1)
Time Complexity: O(n) where n is the number of elements in the list as we are looping through the entire list once.
Auxiliary Space: O(1) as we are not using any extra space for storing the result, just a single variable.
Method #2 : Using list comprehension + enumerate()
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.
Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# Using list comprehension + enumerate()
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
key = 'for'
# Extract Preceding Record
# Using list comprehension + enumerate()
res = [(test_list[idx - 1][0], test_list[idx - 1][1])
for idx, (x, y) in enumerate(test_list) if x == key and idx > 0]
# printing result
print("The Preceding record : " + str(res))
OutputThe original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : [('best', 1)]
Time complexity: O(n) because it iterates through the input list once to find the preceding record.
Auxiliary space: O(1), as it only uses a fixed amount of memory for storing the input list, key, and output list. The list comprehension used to generate the output list doesn't create any additional lists or variables, so the space complexity remains constant regardless of the size of the input list.
Method #3 : Using for loop
Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
key = 'for'
# Extract Preceding Record
for i in range(0,len(test_list)):
if key in test_list[i]:
idx=i
break
res=test_list[idx-1]
# printing result
print("The Preceding record : " + str(res))
OutputThe original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : ('best', 1)
Time Complexity: O(n) where n is the number of elements in the list “test_list”. for loop performs n number of operations.
Auxiliary Space: O(1), constant extra space is required
Method 3: Using enumerate() and a loop:
Step-by-step approach:
- Initialize the list of tuples test_list.
- Initialize the string key with the desired value.
- Use the enumerate() function to loop through the list of tuples along with their indices.
- Use the zip() function to iterate over pairs of adjacent tuples in the list.
- Check if the second element of the tuple in the pair is equal to the key.
- If it is, assign the first element of the first tuple in the pair to res.
- Break out of the loop and print the value of res.
Below is the implementation of the above approach:
Python
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
key = 'for'
# Using enumerate() + loop
for i, (a, b) in enumerate(zip(test_list, test_list[1:])):
if b[0] == key:
res = a
break
print("The Preceding record : " + str(res))
OutputThe Preceding record : ('best', 1)
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #6: Using a dictionary to store the values and their indices
First initialize an empty dictionary and iterate through the original list to store the values and their indices in the dictionary. Then, check if the given key is present in the dictionary. If it is present, retrieve its index and check if it is greater than 0. If it is greater than 0, retrieve the element at index-1 as the preceding record. If it is not greater than 0, set the result to None. Finally, print the result.
Step-by-step approach:
- Initialize an empty dictionary to store the values and their indices.
- Iterate through the original list using a for loop and enumerate() function, and store the values and their indices in the dictionary.
- Check if the given key is present in the dictionary using the 'in' operator.
- If the key is present, retrieve its index from the dictionary.
- Check if the index retrieved is greater than 0
- If the index is greater than 0, retrieve the element at index-1 as the preceding record.
- If the index is not greater than 0, set the result to None.
- Print the result.
Below is the implementation of the above approach:
Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# Using a dictionary to store the values and their indices
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
key = 'for'
# Using a dictionary to store the values and their indices
dictionary = {}
for idx, (a, b) in enumerate(test_list):
dictionary[a] = idx
if key in dictionary:
index = dictionary[key]
if index > 0:
res = test_list[index-1]
else:
res = None
# printing result
print("The Preceding record : " + str(res))
OutputThe original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : ('best', 1)
Time Complexity: O(n), where n is the length of the original list.
Auxiliary Space: O(n), where n is the length of the original list, as we are storing the values and their indices in a dictionary.
Method #7: Using itertools.groupby()
- Import the groupby function from the itertools module.
- Initialize the input list test_list.
- Initialize the key key for the preceding record.
- Use the groupby function to group the elements of test_list based on whether the first element of the tuple is equal to key.
- Use the next function to get the first group of tuples where the first element is not equal to key.
- Convert the iterator of tuples in the preceding group to a list using the list() function.
- Extract the last element of the preceding group using indexing.
- Print the result.
Python3
# Python3 code to demonstrate working of
# Extract Preceding Record
# Using itertools.groupby()
from itertools import groupby
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing Key
key = 'for'
# Extract Preceding Record
# Using itertools.groupby()
groups = groupby(test_list, lambda x: x[0] != key)
preceding_group = list(next(groups)[1])
res = preceding_group[-1]
# printing result
print("The Preceding record : " + str(res))
OutputThe original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The Preceding record : ('best', 1)
Time complexity: O(n), where n is the length of the input list. This is because we are iterating over the input list once.
Auxiliary space: O(1), because we are not using any extra data structures.
Method #8: Using numpy:
- Initialize the list of tuples.
- Initialize the key to be searched in the list.
- Initialize an empty dictionary.
- Traverse the list of tuples using a for loop with an enumerate function, which assigns an index to each tuple.
- Store the key of each tuple as a key and its corresponding index as a value in the dictionary.
- Check if the key exists in the dictionary.
- If the key exists, get the index of the key in the list using the dictionary.
- Check if the index is greater than 0.
- If the index is greater than 0, get the tuple at the index - 1 in the list.
- If the index is 0, assign None to the result.
- Print the preceding record.
Python3
import numpy as np
# initializing list
test_list = [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
# printing original list
print("The original list is : " + str(test_list))
# initializing key
key = 'for'
# convert list of tuples to NumPy array
arr = np.array(test_list)
# get index of key in the array
idx = np.where(arr[:,0] == key)[0]
# if key is found and has a preceding record, return it
if len(idx) > 0 and idx > 0:
res = arr[idx-1]
else:
res = None
# print result
print("The preceding record: " + str(res))
#This code is contributed by Jyothi pinjala.
Output:
The original list is : [('Gfg', 3), ('is', 4), ('best', 1), ('for', 10), ('geeks', 11)]
The preceding record: [['best' '1']]
Time complexity:
The time complexity is O(n), where n is the number of elements in the list. Converting the list to a NumPy array using the np.array() function takes O(n) time, and searching for the index of the key in the array using the np.where() function takes O(n) time in the worst case. Extracting the preceding record from the array takes O(1) time.
Space complexity:
The space complexity is O(n), where n is the number of elements in the list. This is because we need to store the list in a NumPy array, which has the same length as the list. We also need to store the indices of the elements in the array that are equal to the key, which has a maximum length of n. The space complexity of the other variables and the returned result is not included in the analysis.
Similar Reads
Python - Values from custom List in Records
Sometimes, while working with Python records, we can have a problem in which we need to extract all the values from the custom list in list dictionary records. This problem can have applications in domains such as web development and school programming. Let's discuss certain ways in which this task
7 min read
Python - Value Dictionary from Record List
Sometimes, while working with Python Records lists, we can have problems in which, we need to reform the dictionary taking just values of the binary dictionary. This can have applications in many domains which work with data. Let us discuss certain ways in which this task can be performed. Method #1
6 min read
Python - Rear element extraction from list of tuples records
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let's discuss certain ways in which one
8 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 - Find minimum k records from tuple list
Sometimes, while working with data, we can have a problem in which we have records and we require to find the lowest K scores from it. This kind of application is popular in web development domain. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambda Th
6 min read
Python - Tuple key detection from value list
Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed. Method #1 : Using
6 min read
Python | Index minimum value Record
In Python, we can bind structural information in the form of tuples and then can retrieve the same, and has manyfold applications. But sometimes we require the information of a tuple corresponding to a minimum value of another tuple index. This functionality has many applications such as ranking. Le
4 min read
Python - Extract digits from Tuple list
Sometimes, while working with Python lists, we can have a problem in which we need to perform extraction of all the digits from tuple list. This kind of problem can find its application in data domains and day-day programming. Let's discuss certain ways in which this task can be performed. Input : t
6 min read
Python | Extract Nth words in Strings List
Sometimes, while working with Python Lists, we can have problems in which we need to perform the task of extracting Nth word of each string in List. This can have applications in the web-development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using list compreh
7 min read
Python - Extract records if Kth elements not in List
Given list of tuples, task is to extract all the tuples where Kth index elements are not present in argument list. Input : test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)], arg_list = [6, 8, 8], K = 1 Output : [(5, 3), (7, 4), (1, 3)] Explanation : All the elements which have either 6 or 8 at 1s
4 min read