Python – Remove Record if Nth Column is K

Sometimes while working with list of records, we can have a problem in which we need to perform removal of records on the basis of presence of certain element at Nth position of record. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is 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.

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

Method #2 : Using list comprehension
This is yet another way in which this task can be performed. In this, we perform this task in similar way as above but in one liner form.

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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.