Write a Python program to Filter Tuples by Kth element from List


The program filters a list of tuples based on the values in a given list and returns a new list of tuples that meet a specific criteria. Here's what happens step-by-step:

  • The val list is defined and initialized with 4 tuples.
  • The original val list is printed using the following line:
    • print("The original list is : " + str(val))
  • The l list is defined and initialized with a list of 5 integers.
  • The K variable is defined and initialized with the value 1.
  • The res list is created using a list comprehension. The list comprehension iterates over the elements in val and for each tuple, it retrieves the second element (index 1) and checks if it is present in the l list. If it is, the entire tuple is appended to the res list:
    • res = [s for s in val if s[K] in l]
  • The res list is printed using the following line:
    • print("The filtered tuples : " + str(res))

So the program filters the original val list based on the values present in the l list and returns a new list of tuples that meet the criteria.

Source Code

val = [('B', 68), ('D', 70), ('A', 67), ('C', 69)]
print("The original list is : " + str(val))
l = [67 , 70 , 71, 75]
K = 1
res = [s for s in val if s[K] in l]
print("The filtered tuples : " + str(res))

Output

The original list is : [('B', 68), ('D', 70), ('A', 67), ('C', 69)]
The filtered tuples : [('D', 70), ('A', 67)]

Example Programs