Syntax error Filter Tuples by Kth element from List in Python

Filter Tuples by Kth element from List in Python



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.
Updated on: 2021-03-11T09:47:37+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements