Filter Tuples by Kth element from List in Python

PythonServer Side ProgrammingProgramming

When it is required to filter the tuples by the 'K'th element from a list, list comprehension and 'in' operators can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list. The 'in' operators checks to see if the specific data is present in the iterable/data or not.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

Below is a demonstration of the same −

Example

Live Demo

my_list = [(1, 21), (25, 'abc', 'mnq'), (89, 45.65)]

print("The check list has been initialized")
check_list = [1, 25, 10, 21]
print("The list is :")
print(my_list)
k=1
print("The 'k' value has been initialized to 1")

my_result = [elem for elem in my_list if elem[k] in check_list]

print("The filtered tuples are : ")
print(my_result)

Output

The check list has been initialized
The list is :
[(1, 21), (25, 'abc', 'mnq'), (89, 45.65)]
The 'k' value has been initialized to 1
The filtered tuples are :
[(1, 21)]

Explanation

  • A list of tuple is defined, and displayed on the console.
  • Another list is defined, and displayed on the console.
  • The value of 'k' is initialized.
  • The lists are iterated over to check if the element in the second list is present in the first list.
  • If it is present, it is retained in the list, else it is eliminated
  • This is then converted to a list.
  • This operation is assigned to a variable.
  • This variable is the output that is displayed on the console.
raja
Published on 11-Mar-2021 09:42:32
Advertisements