
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Filter Tuples with Strings of Specific Characters in Python
When it is required to filter tuples with strings that have specific characters, a list comprehension and the ‘all’ operator is used.
Example
Below is a demonstration of the same −
my_list = [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')] print("The list is :") print(my_list) char_string = 'pyestb' my_result = [index for index in my_list if all(all(sub in char_string for sub in element) for element in index)] print("The result is : ") print(my_result)
Output
The list is : [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')] The result is : [('pyt', 'best')]
Explanation
A list of tuple is defined and displayed on the console.
A string is defined.
A list comprehension is used to iterate over the list and ‘all’ operator is used on elements to check if that specific string is present in any elements of the list.
This is converted to a list and is assigned to a variable.
This is the output that is displayed on the console.
Advertisements