Python – Remove Record if Nth Column is K

Last Updated : 08 May, 2023

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:

1. Initialize a list called test_list with tuples as elements.
2. Print the original list using the print() function and the str() function to convert the list to a string.
3. Initialize variables K and N with integer values.
4. Create an empty list called res.
5. Use a for loop to iterate over each element in test_list.
6. Use an if statement to check if the Nth column of the current tuple is not equal to K.
7. If the Nth column is not equal to K, append the current tuple to the res list.
8. 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

 `# Python3 code to demonstrate` `# Remove Record if Nth Column is K` `# using loop`   `# Initializing list` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Initializing K` `K ``=` `7`   `# Initializing N` `N ``=` `1`   `# Remove Record if Nth Column is K` `# using loop` `res ``=` `[]` `for` `sub ``in` `test_list:` `    ``if` `(sub[N] !``=` `K):` `      `  `        ``res.append(sub)`   `# printing result` `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

 `# Python3 code to demonstrate` `# Remove Record if Nth Column is K` `# using list comprehension`   `# Initializing list` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Initializing K` `K ``=` `7`   `# Initializing N` `N ``=` `1`   `# Remove Record if Nth Column is K` `# using list comprehension` `res ``=` `[sub ``for` `sub ``in` `test_list ``if` `sub[N] !``=` `K]`   `# printing result` `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

 `# Python3 code to demonstrate` `# Remove Record if Nth Column is K` `# using filter() + itemgetter()`   `# Initializing list` `from` `operator ``import` `itemgetter` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Initializing K` `K ``=` `7`   `# Initializing N` `N ``=` `1`   `# Remove Record if Nth Column is K` `# using filter() + itemgetter()` `res ``=` `list``(``filter``(``lambda` `sub: itemgetter(N)(sub) !``=` `K, test_list))`   `# printing result` `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)
Auxiliary Space: O(n)

Method #4:  Using list comprehension and the built-in any() function

Algorithm:

1. Initialize the input list of tuples, test_list.
2. Define the index of the column to check, N.
3. Define the value to check against, K.
4. 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.
5. Print the resulting list, res.

Python3

 `# define the list of tuples` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# define the index of the column to check` `N ``=` `1`   `# define the value to check against` `K ``=` `7`   `# Use list comprehension to create a new list ` `# containing only the tuples that` `# do not have a value of K in the Nth column` `res ``=` `[t ``for` `t ``in` `test_list ``if` `not` `any``(` `    ``x ``=``=` `K ``for` `i, x ``in` `enumerate``(t) ``if` `i ``=``=` `N)]`   `# Printing the resultant list ` `print``(``"List after removal: "` `+` `str``(res))`

Output

`List 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

1. Define a list test_list containing the input tuples.
2. Define N as the index of the column to check and K as the value to check against.
3. 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.
4. Create an empty numpy array res_arr with dtype=object.
5. Set the values of the array equal to the values in res_list. This avoids the inhomogeneous shape error.
6. 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` `# printing original list` `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))`   `# This code is contributed by Jyothi pinjala`

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:

1. Initialize the list ‘test_list’ with tuples containing integers.
2. Print the original list using the ‘print()’ function.
3. Initialize the value of ‘K’ and ‘N’.
4. 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’.
5. Use the ‘filter()’ method to filter the tuples that do not satisfy the lambda condition and store the filtered tuples in a list ‘res’.
6. Print the resultant list using the ‘print()’ function.

Python3

 `# Python3 code to demonstrate` `# Remove Record if Nth Column is K` `# using lambda function and filter() method`   `# Initializing list` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Initializing K` `K ``=` `7`   `# Initializing N` `N ``=` `1`   `# Remove Record if Nth Column is K` `# using lambda function and filter() method` `res ``=` `list``(``filter``(``lambda` `x: x[N] !``=` `K, test_list))`   `# printing result` `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)
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

 `# Python3 code to demonstrate` `# Remove Record if Nth Column is K` `# using list slicing and concatenation`   `# Initializing list` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Initializing K` `K ``=` `7`   `# Initializing N` `N ``=` `1`   `# Remove Record if Nth Column is K` `res ``=` `[tup ``for` `tup ``in` `test_list ``if` `tup[N] !``=` `K]`   `# printing result` `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)
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

 `# Python3 code to demonstrate` `# Remove Record if Nth Column is K` `# using the itertools module`   `# import the itertools module` `import` `itertools`   `# Initializing list` `test_list ``=` `[(``5``, ``7``), (``6``, ``7``, ``8``), (``7``, ``8``, ``10``), (``7``, ``1``)]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# Initializing K` `K ``=` `7`   `# Initializing N` `N ``=` `1`   `# Using the itertools module to remove record` `res ``=` `list``(itertools.filterfalse(``lambda` `tup: tup[N] ``=``=` `K, test_list))`   `# printing result` `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 number of tuples in the input list.
Auxiliary space: O(n), where n is the number of tuples in the input list.