Python – Remove Record if Nth Column is K
Last Updated :
25 Apr, 2025
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 a brute force method in which this task can be performed. In this, we iterate for each element in list and exclude it if its Nth column is equal to K.
Approach:
- Initialize a list called test_list with tuples as elements.
- Print the original list using the print() function and the str() function to convert the list to a string.
- Initialize variables K and N with integer values.
- Create an empty list called res.
- Use a for loop to iterate over each element in test_list.
- Use an if statement to check if the Nth column of the current tuple is not equal to K.
- If the Nth column is not equal to K, append the current tuple to the res list.
- After the loop has been completed, print the updated list using the print() function and the str() function to convert the list to a string.
Python3
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
print ( "The original list is : " + str (test_list))
K = 7
N = 1
res = []
for sub in test_list:
if (sub[N] ! = K):
res.append(sub)
print ( "List after removal : " + str (res))
|
Output : The original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using list comprehension
This is yet another way in which this task can be performed. In this, we perform this task in a similar way as above but in one-liner form.
Python3
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
print ( "The original list is : " + str (test_list))
K = 7
N = 1
res = [sub for sub in test_list if sub[N] ! = K]
print ( "List after removal : " + str (res))
|
Output : The original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
Method #3: Using filter() + itemgetter()
This is yet another way in which this task can be performed. In this, we employ the inbuilt itemgetter to perform the task.
Python3
from operator import itemgetter
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
print ( "The original list is : " + str (test_list))
K = 7
N = 1
res = list ( filter ( lambda sub: itemgetter(N)(sub) ! = K, test_list))
print ( "List after removal : " + str (res))
|
OutputThe original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using list comprehension and the built-in any() function
Algorithm:
- Initialize the input list of tuples, test_list.
- Define the index of the column to check, N.
- Define the value to check against, K.
- Use a list comprehension to create a new list res, which contains only the tuples in test_list that do not have a value of K in the N-th column.
- Print the resulting list, res.
Python3
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
N = 1
K = 7
res = [t for t in test_list if not any (
x = = K for i, x in enumerate (t) if i = = N)]
print ( "List after removal: " + str (res))
|
OutputList after removal: [(7, 8, 10), (7, 1)]
Time complexity: O(NM)
The time complexity of the list comprehension is O(nm), where n is the number of tuples in test_list and m is the maximum length of a tuple in the list. This is because the comprehension iterates over each tuple in test_list and performs a check for each item in the tuple (up to m checks per tuple). The time complexity of the print statement is O(n), as it simply iterates over the resulting list to print its elements. Therefore, the overall time complexity is O(nm).
Auxiliary space: O(N)
The space complexity of the list comprehension is O(n), as it creates a new list of tuples containing only the elements that meet the specified condition. The space complexity of the print statement is also O(n), as it prints each element of the resulting list. Therefore, the overall space complexity is O(n).
Method #5: Using the numpy Module
- Define a list test_list containing the input tuples.
- Define N as the index of the column to check and K as the value to check against.
- Create a new list res_list containing only the tuples that do not have a value of K in the Nth column, and have a length greater than N. This is done using a list comprehension.
- Create an empty numpy array res_arr with dtype=object.
- Set the values of the array equal to the values in res_list. This avoids the inhomogeneous shape error.
- Print the resulting numpy array.
Python3
import numpy as np
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
N = 1
K = 7
print ( "The original list is : " + str (test_list))
res_list = [t for t in test_list if len (t) > N and t[N] ! = K]
res_arr = np.empty( len (res_list), dtype = object )
res_arr[:] = res_list
print ( "Array after removal: " + str (res_arr))
|
Output:
The original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
Array after removal: [(7, 8, 10) (7, 1)]
Time complexity: O(n + m)
The list comprehension to create res_list has a time complexity of O(n), where n is the number of tuples in the input list.
The numpy array creation has a time complexity of O(m), where m is the number of tuples in res_list.
Overall, the time complexity of the code is O(n + m).
Auxiliary Space: O(n + m)
The space complexity of the list comprehension to create res_list is O(n), since we are creating a new list of tuples.
The space complexity of the numpy array res_arr is O(m), since we are creating a new array to store the filtered tuples.
Overall, the space complexity of the code is O(n + m).
Method #6: Using lambda function and filter() method
Here’s the step-by-step approach to solve the problem using lambda function and filter() method:
- Initialize the list ‘test_list’ with tuples containing integers.
- Print the original list using the ‘print()’ function.
- Initialize the value of ‘K’ and ‘N’.
- Create a lambda function that takes a tuple as input and returns ‘True’ if the Nth element of the tuple is not equal to ‘K’.
- Use the ‘filter()’ method to filter the tuples that do not satisfy the lambda condition and store the filtered tuples in a list ‘res’.
- Print the resultant list using the ‘print()’ function.
Python3
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
print ( "The original list is : " + str (test_list))
K = 7
N = 1
res = list ( filter ( lambda x: x[N] ! = K, test_list))
print ( "List after removal : " + str (res))
|
OutputThe original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
Time complexity: O(n)
Auxiliary space: O(n) where ‘n’ is the number of tuples in the list.
Method 7: Use list slicing and concatenation to remove the desired record
Python3
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
print ( "The original list is : " + str (test_list))
K = 7
N = 1
res = [tup for tup in test_list if tup[N] ! = K]
print ( "List after removal : " + str (res))
|
OutputThe original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
Time complexity: O(n)
Auxiliary space: O(n) where ‘n’ is the number of tuples in the list.
Method 8 : Using the itertools module
- Import the itertools module.
- Initialize list test_list, K, and N as given in the problem statement.
- Use the itertools.filterfalse() function to filter out tuples that have K in the Nth column. This function returns an iterator that yields all items from the iterable for which the function returns False.
- Define a lambda function that takes a tuple as input and returns True if the Nth element of the tuple is not equal to K. This lambda function will be used as the filtering function in the filterfalse() function.
- Use the list() function to convert the iterator to a list.
- Print the resulting list.
Python3
import itertools
test_list = [( 5 , 7 ), ( 6 , 7 , 8 ), ( 7 , 8 , 10 ), ( 7 , 1 )]
print ( "The original list is : " + str (test_list))
K = 7
N = 1
res = list (itertools.filterfalse( lambda tup: tup[N] = = K, test_list))
print ( "List after removal : " + str (res))
|
OutputThe original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), where n is the number of tuples in the input list.
Similar Reads
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
Python - Remove None Nested Records
Sometimes, while working with Python Records, can have problem in which we need to perform the removal of data which have all key's values as None in nested records. This kind of problem can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method
4 min read
Python - Remove Consecutive K element records
Sometimes, while working with Python records, we can have a problem in which we need to remove records on the basis of presence of consecutive K elements in tuple. This kind of problem is peculiar but can have applications in data domains. Let's discuss certain ways in which this task can be perform
7 min read
Python - Remove nested records from tuple
Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Letâs discuss certain way in which this task c
5 min read
Python - Remove front column from Matrix
Sometimes, while working with Matrix data, we can have stray element that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Letâs discuss certain ways in which this task can be performed. Method #1: Using loop + del + list slicing The combination o
6 min read
Python | Remove Initial K column elements
Sometimes, while working with Matrix data, we can have stray elements that attached at front end of each row of matrix. This can be undesired at times and wished to be removed. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop + del + list slicing The combination
4 min read
Remove Kth Key from Dictionary - Python
We are given a dictionary we need to remove Kth key from the dictionary. For example, we are given a dictionary d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} we need to remove the key2 so that the output should be {'key1': 'value1', 'key3': 'value3', 'key4': 'value4'}.
3 min read
Python - Remove Dictionary if Given Key's Value is N
We are given a dictionary we need to remove key if the given value of key is N. For example, we are given a dictionary d = {'a': 1, 'b': 2, 'c': 3} we need to remove the key if the value is N so that the output becomes {'a': 1, 'c': 3}. We can use methods like del, pop and various other methods like
2 min read
Python - Custom Rows Removal depending on Kth Column
Sometimes, while working with Python Matrix, we can have a problem in which we need to remove elements from Matrix depending on its Kth Column element present in the argument list. This can have application in many domains. Let us discuss certain ways in which this task can be performed. Method #1:
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