Skip to content
Related Articles
Python | Find the tuples containing the given element from a list of tuples
• Last Updated : 15 Feb, 2019

Given a list of tuples, the task is to find all those tuples containing the given element, say n.

Examples:

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.

 `# Python code to find the tuples containing``# the given element from a list of tuples`` ` `# List of tuples``Input` `=` `[(``14``, ``3``),(``23``, ``41``),(``33``, ``62``),(``1``, ``3``),(``3``, ``3``)]`` ` `# Find an element in list of tuples.``Output ``=` `[item ``for` `item ``in` `Input` `          ``if` `item[``0``] ``=``=` `3` `or` `item[``1``] ``=``=` `3``]`` ` `# printing output``print``(Output)`
Output:
```[(14, 3), (1, 3), (3, 3)]
```

Method #1 : Using `filter` In this solution, there can be variable number of nodes in lists.

 `# Python code to find the tuples containing``# the given element from a list of tuples`` ` `# List of tuples``Input` `=` `[(``11``, ``22``), (``33``, ``55``), (``55``, ``77``),``         ``(``11``, ``44``), (``33``, ``22``, ``100``, ``11``), (``99``, ``11``)]`` ` `# Using filter``Output ``=` `list``(``filter``(``lambda` `x:``11` `in` `x, ``Input``))`` ` `# Prinitng output``print``(Output)`
Output:
```[(11, 22), (11, 44), (33, 22, 100, 11), (99, 11)]
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up