Open In App

Python – Records with Value at K index

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.



Last Updated : 12 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads