- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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)
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)]
- 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.
- Filter tuples according to list element presence in Python
- Python - Filter dictionaries by values in Kth Key in list
- Accessing nth element from Python tuples in list
- Python – Filter all uppercase characters from given list of tuples
- Rear element extraction from list of tuples records in Python
- Find the tuples containing the given element from a list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Remove Tuples from the List having every element as None in Python
- Python – Remove Tuples from a List having every element as None
- Python – Filter Tuples with Integers
- Python – Filter unique valued tuples
- Python – Filter consecutive elements Tuples
- Python – Extract Kth element of every Nth tuple in List
- Remove tuples from list of tuples if greater than n in Python
- Python – Replace value by Kth index value in Dictionary List