Open In App

Python – Records with Value at K index

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


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)
Auxiliary Space: o(n)

Method#4: Using Recursive method.

Algorithm:

  1. 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.
  2. Check if the list is empty or not, if empty return an empty list.
  3. 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.
  4. 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.
  5. Repeat step 2-4 until the entire list has been traversed.
  6. 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


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)]

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))


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 the input list.
Auxiliary space: O(k), where k is the number of tuples that satisfy the condition.

Method 6: Using numpy:

algorithm:

  1. Import the numpy library.
  2. Initialize the list test_list.
  3. Initialize the integer ele with the value 3.
  4. Initialize the integer K with the value 1.
  5. Use numpy’s array method to convert the list test_list to a numpy array.
  6. Use boolean indexing to filter the numpy array test_list to get only the tuples where the element at the Kth
  7. index is equal to ele.
  8. Convert the resulting numpy array back to a list using the tolist() method.
  9. 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 | Minimum K records of Nth index in tuple list
Sometimes, while working with data, we can have a problem in which we need to get the minimum of elements filtered by the Nth element of record. This has a very important utility in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using filter() + lambda + set() + list comprehension The combination
9 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 web development. Let's discuss certain way in which
4 min read
Python - Group Records on Similar index elements
Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of particular index of tuple, on basis of similarity of rest of indices. This type of problems can have possible applications in Web development domain. Let's discuss certain ways in which this task can be performed. Input : test_list = [(4, 5,
6 min read
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 performed. For this, we just use naive check and c
7 min read
Python | Selective Records Value Summation
Sometimes, while using a list of tuples, we come across a problem in which we have e certain list of keys and we just need the summation of values of those keys from the list of tuples. This has a utility in rating or summation of specific entities. Let’s discuss certain ways in which this can be done. Method #1: Using dict() + sum() + get() + list
11 min read
Python - Convert Value list elements to List records
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert the nested list values to individual records to include another level of nesting to accommodate data. This kind of problem can have applications in data domains such as web development and Machine Learning. Let's discuss certain ways in which this t
6 min read
Python - Replace value by Kth index value in Dictionary List
Given a dictionary list, the task is to write a Python program to replace the value of a particular key with kth index of value if the value of the key is list. Examples: Input : test_list = [{'gfg' : [5, 7, 9, 1], 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : [7, 3, 9, 1]}], K = 2, key = "gfg" Output : [{'gfg':
7 min read
Python Program to get value of a dictionary given by index of maximum value of given key
Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key's values. Approach : Get the maximum of the given key.Get the index of the maximum element found.Check if the index of max is present in the search key, if not, return Result not Poss
8 min read
Python | Retain records of specific length
Sometimes, while working with records, we might desire to filter records in such a way in we need to discard records that do not contain an exact number of elements required to constitute a record. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + len() In this method, we just iterate through the
11 min read
Python | Convert tuple records to single string
Sometimes, while working with data, we can have a problem in which we have tuple records and we need to change it's to comma-separated strings. These can be data regarding names. This kind of problem has its application in the web development domain. Let's discuss certain ways in which this problem can be solved Method #1: Using join() + list compr
6 min read