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 - Remove Keys with K value
We are given a dictionary we need to remove the keys with K value. For example, we are having a dictionary d = {'a': 1, 'b': 2, 'c': 1, 'd': 3} we need to remove the keys which is having K value so that the output should be {'b': 2, 'd': 3} . We can use dictionary comprehension and many other method
3 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 - Remove Kth Index Duplicates in Tuple
Sometimes, while working with Python records, we can have a problem in which we need to remove all the tuples, which have similar Kth index elements in list of records. This kind of problem is common in day-day and web development domain. Let's discuss certain ways in which this task can be performe
7 min read
Python - Row with Maximum Record Element
Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [
7 min read
Python - Remove K from Records
Sometimes, while working with Python tuples, we can have a problem in which we need to remove all K from lists. This task can have application in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [(5, 6,
5 min read