Given a list of tuples, the task is to find all those tuples containing the given element, say n.
Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)]
Output: [(11, 22), (11, 44)]
Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)]
Output: [(14, 3), (1, 3), (3, 3)]
There are multiple ways we can find the tuples containing the given element from a list of tuples. Let’s see some of Pythonic ways to do this task.
Method #2: Using list comprehension. It works only when there are fixed number of elements in every list. For example 2 elements in below code.
[(14, 3), (1, 3), (3, 3)]
Method #1 : Using
filter In this solution, there can be variable number of nodes in lists.
[(11, 22), (11, 44), (33, 22, 100, 11), (99, 11)]
- Python | Remove tuples from list of tuples if greater than n
- Python | Accessing nth element from tuples in list
- Python | Get first element with maximum value in list of tuples
- Python | Min and Max value in list of tuples
- Python | Unzip a list of tuples
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Check if element is present in tuple of tuples
- Python | Remove empty tuples from a list
- Python | Linear search on list or tuples
- Output of Python Programs | Set 18 (List and Tuples)
- Python | Merge two lists into list of tuples
- Python | Convert dictionary to list of tuples
- Python | Convert list of tuples into digits
- Python | Finding frequency in list of tuples
- Python | Position Summation in List of Tuples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.