
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the tuples containing the given element from a list of tuples in Python
A list can have tuples as its elements. In this article we will learn how to identify those tuples which contain a specific search element which is a string.
With in and condition
We can design a follow with in condition. After in we can mention the condition or a combination of conditions.
Example
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)] test_elem = 'Mon' #Given list print("Given list:\n",listA) print("Check value:\n",test_elem) # Uisng for and if res = [item for item in listA if item[0] == test_elem and item[1] >= 2] # printing res print("The tuples satisfying the conditions:\n ",res)
Output
Running the above code gives us the following result −
Given list: [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)] Check value: Mon The tuples satisfying the conditions: [('Mon', 3), ('Mon', 2)]
With filter
We use the filter function along with Lambda function. In the filter condition we use the the in operator to check for the presence of the element in the tuple.
Example
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)] test_elem = 'Mon' #Given list print("Given list:\n",listA) print("Check value:\n",test_elem) # Uisng lambda and in res = list(filter(lambda x:test_elem in x, listA)) # printing res print("The tuples satisfying the conditions:\n ",res)
Output
Running the above code gives us the following result −
Given list: [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)] Check value: Mon The tuples satisfying the conditions: [('Mon', 3), ('Mon', 2)]
- Related Questions & Answers
- Remove duplicate tuples from list of tuples in Python
- Remove tuples having duplicate first value from given list of tuples in Python
- Accessing nth element from Python tuples in list
- Combining tuples in list of tuples in Python
- Rear element extraction from list of tuples records in Python
- Filter Tuples by Kth element from List in Python
- Python program to find Tuples with positive elements in a List of tuples
- Remove tuple from list of tuples if not containing any character in Python
- Count tuples occurrence in list of tuples in Python
- Remove tuples from list of tuples if greater than n in Python
- Python program to find Tuples with positive elements in List of tuples
- Remove Tuples from the List having every element as None in Python
- Python | Remove empty tuples from a list
- Python program to find tuples which have all elements divisible by K from a list of tuples
- Python – Filter all uppercase characters from given list of tuples
Advertisements