Python – Filter Tuples with Strings of specific characters

PythonServer Side ProgrammingProgramming

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.

raja
Published on 08-Sep-2021 10:41:53
Advertisements