Python | Find the tuples containing the given element from a list of tuples

• Difficulty Level : Basic
• Last Updated : 16 Aug, 2022

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 #1: Using list comprehension. It works only when there are fixed number of elements in every list. For example 2 elements in below code.

Python3

 `# 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 #2 : Using filter In this solution, there can be variable number of nodes in lists.

Python3

 `# 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``))` `# Printing output``print``(Output)`

Output:

`[(11, 22), (11, 44), (33, 22, 100, 11), (99, 11)]`

My Personal Notes arrow_drop_up