Python - Records with Value at K index
Last Updated :
12 Apr, 2023
Sometimes, while working with records, we might have a problem in which we need to find all the tuples of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop This is the brute force method by which this problem can be solved. In this we keep a check and append to list if we find specific record at Kth position in tuple.
Python3
# Python3 code to demonstrate working of
# Records with Value at K index
# Using loop
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 3
# initialize K
K = 1
# Records with Value at K index
# Using loop
# using y for K = 1
res = []
for x, y, z in test_list:
if y == ele:
res.append((x, y, z))
# printing result
print("The tuples of element at Kth position : " + str(res))
Output : The original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The tuples of element at Kth position : [(1, 3, 6), (6, 3, 0)]
Time complexity: O(n), where n is the number of tuples in input list.
Auxiliary space: O(k), where k is the number of tuples that satisfy the condition.
Method #2 : Using enumerate() + list comprehension The combination of above functions can be used to solve this problem. In this, we enumerate for the indices using enumerate(), rest is performed as in above method but in compact way.
Python3
# Python3 code to demonstrate working of
# Records with Value at K index
# Using enumerate() + list comprehension
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 3
# initialize K
K = 1
# Records with Value at K index
# Using enumerate() + list comprehension
res = [b for a, b in enumerate(test_list) if b[K] == ele]
# printing result
print("The tuples of element at Kth position : " + str(res))
Output : The original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The tuples of element at Kth position : [(1, 3, 6), (6, 3, 0)]
Method #3 : Using filter()
This is yet another approach to solve this problem. In this, we simply use filter() to check if the element at Kth position is equal to the element to be searched, if yes, then only we append to the list.
Python3
# Python3 code to demonstrate working of
# Records with Value at K index
# Using filter()
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 3
# initialize K
K = 1
# Records with Value at K index
# Using filter()
res = list(filter(lambda x : x[K] == ele, test_list))
# printing result
print("The tuples of element at Kth position : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The tuples of element at Kth position : [(1, 3, 6), (6, 3, 0)]
Time complexity: o(n)
Auxiliary Space: o(n)
Method#4: Using Recursive method.
Algorithm:
- Define the function filter_by_index(lst, ele, k), which takes a list of tuples, an element to be searched for in the kth index, and kth index position of the tuples.
- Check if the list is empty or not, if empty return an empty list.
- If the kth index of the first tuple of the list matches with the element ele, return a list containing that tuple concatenated with a recursive call of the function using the remaining list and the same parameters ele and k.
- If the kth index of the first tuple of the list does not match with the element ele, discard that tuple and return a recursive call of the function using the remaining list and the same parameters ele and k.
- Repeat step 2-4 until the entire list has been traversed.
- Return the final list containing all tuples that match the condition.
Python3
def filter_by_index(lst, ele, k):
if not lst:
return []
if lst[0][k] == ele:
return [lst[0]] + filter_by_index(lst[1:], ele, k)
else:
return filter_by_index(lst[1:], ele, k)
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 3
# initialize K
K = 1
res = filter_by_index(test_list,ele,K)
# printing result
print("The tuples of element at Kth position : " + str(res))
#this code contributed by tvsk
OutputThe original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The tuples of element at Kth position : [(1, 3, 6), (6, 3, 0)]
The time complexity of this function is O(n), where n is the length of the input list 'lst'. This is because the function iterates over each element of the list once.
The space complexity of this function is also O(n), where n is the length of the input list 'lst'. This is because the function creates a new list to store the filtered tuples, and the size of this list is at most n.
Method 5: using the map() function along with a lambda function to filter the tuples based on the value at the K index
- Define the input list of tuples.
- Initialize the value ele to the element to be searched for at the K index.
- Initialize the value K to the index at which the search for the element needs to be performed.
- Use the filter() function along with a lambda function to create a new list of tuples that satisfy the condition of having the element ele at the K index.
- Convert the filtered object into a list to obtain the final result.
Python3
# Python3 code to demonstrate working of
# Records with Value at K index
# Using map() and lambda function
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# printing original list
print("The original list is : " + str(test_list))
# initialize ele
ele = 3
# initialize K
K = 1
# Records with Value at K index
# Using map() and lambda function
res = list(filter(lambda tup: tup[K] == ele, test_list))
# printing result
print("The tuples of element at Kth position : " + str(res))
OutputThe original list is : [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
The tuples of element at Kth position : [(1, 3, 6), (6, 3, 0)]
Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(k), where k is the number of tuples that satisfy the condition.
Method 6: Using numpy:
algorithm:
- Import the numpy library.
- Initialize the list test_list.
- Initialize the integer ele with the value 3.
- Initialize the integer K with the value 1.
- Use numpy's array method to convert the list test_list to a numpy array.
- Use boolean indexing to filter the numpy array test_list to get only the tuples where the element at the Kth
- index is equal to ele.
- Convert the resulting numpy array back to a list using the tolist() method.
- Print the resulting list.
Python3
import numpy as np
# Initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 5, 7), (5, 2, 8), (6, 3, 0)]
# Initialize ele
ele = 3
# Initialize K
K = 1
# Records with Value at K index using numpy
res = np.array(test_list)[np.array(test_list)[:, K] == ele]
# Printing result
print("The tuples of element at Kth position : " + str(res.tolist()))
#this code is contributed by Rayudu.
Output:
The tuples of element at Kth position : [[1, 3, 6], [6, 3, 0]]
Time complexity: The time complexity of this code is O(n), where n is the length of the input list test_list. This is because the numpy array is created in O(n) time and the boolean indexing operation is performed in O(n) time.
Space complexity: The space complexity of this code is also O(n), where n is the length of the input list test_list. This is because the numpy array created using np.array(test_list) takes O(n) space and the resulting filtered list also takes O(n) space.
Similar Reads
Python | Records with Key's value greater than K The problem of getting the suitable dictionaries that has a atleast value of the corresponding key is quite common when one starts working with dictionary. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop This is the brute force method by which this task can be
7 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 - Dictionary with Index as Value We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}.Using Dictionary ComprehensionWe can use dictionary comprehens
2 min read
Python - Sort Records by Kth Index List Sometimes, while working with Python Records, we can have a problem in which we need to perform Sorting of Records by some element in Tuple, this can again be sometimes, a list and sorting has to performed by Kth index of that list. This is uncommon problem, but can have usecase in domains such as w
4 min read
Python | Exponentiate Kth Record Index Many times, while working with records, we can have a problem in which we need to change the value of tuple elements. This is a common problem while working with tuples. Letâs discuss certain ways in which N can be exponentiated to Kth element of tuple in list. Method #1 : Using loop Using loops thi
5 min read
Python - Retain records with N occurrences of K Sometimes, while working with Python tuples list, we can have a problem in which we need to perform retention of all the records where occurrences of K is N times. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task
10 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 - Ways to find indices of value in list In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python - Remove Record if Nth Column is K Sometimes while working with a list of records, we can have a problem in which we need to perform the removal of records on the basis of the presence of certain elements at the Nth position of the record. Let us discuss certain ways in which this task can be performed. Method #1: Using loop This is
10 min read
Python - Element Index in Range Tuples Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
7 min read