Python - Filter Tuples with Strings of specific characters
Last Updated :
24 Apr, 2023
Given a Tuple List, extract tuples, which have strings made up of certain characters.
Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfestb'
Output : [('gfg', 'best'), ('fest', 'gfg')]
Explanation : All tuples contain characters from char_str.
Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfstb'
Output : []
Explanation : No tuples with given characters.
Method #1 : Using all() + list comprehension
In this, we check for characters in strings, using in operator and all() is used to check if all elements in tuple have strings made up of certain characters.
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# Using all() + list comprehension
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
# printing original lists
print("The original list is : " + str(test_list))
# initializing char_str
char_str = 'gfestb'
# nested all(), to check for all characters in list,
# and for all strings in tuples
res = [sub for sub in test_list if all(
all(el in char_str for el in ele) for ele in sub)]
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
The filtered tuples : [('gfg', 'best'), ('fest', 'gfg')]
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #2 : Using filter() + lambda + all()
Similar to the above method, difference being filter() + lambda is used to perform task of filtering.
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# Using filter() + lambda + all()
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
# printing original lists
print("The original list is : " + str(test_list))
# initializing char_str
char_str = 'gfestb'
# nested all(), to check for all characters in list,
# and for all strings in tuples filter() is used
# to extract tuples
res = list(filter(lambda sub: all(all(el in char_str for el in ele)
for ele in sub), test_list))
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
The filtered tuples : [('gfg', 'best'), ('fest', 'gfg')]
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #3 : Using replace(),join() and len() methods
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
# printing original lists
print("The original list is : " + str(test_list))
# initializing char_str
char_str = 'gfestb'
res=[]
for i in test_list:
x="".join(i)
for j in char_str:
x=x.replace(j,"")
if(len(x)==0):
res.append(i)
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
The filtered tuples : [('gfg', 'best'), ('fest', 'gfg')]
Time complexity: O(n*m), where n is the length of the input list and m is the length of the char_str.
Auxiliary space: O(k), where k is the number of tuples that satisfy the condition, as we are storing those tuples in a new list.
Method #4 : Using re
One approach to solve this problem is using a regular expression. The idea is to join the tuples into a single string and then use re.search to check if all characters are in the character string. Here is the code:
Python3
import re
def filter_tuples(test_list, char_str):
res = []
for sub in test_list:
x = "".join(sub)
if re.search("^[" + char_str + "]+$", x):
res.append(sub)
return res
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
char_str = 'gfestb'
print(filter_tuples(test_list, char_str))
Output[('gfg', 'best'), ('fest', 'gfg')]
Time complexity: O(n^2)
Auxiliary Space: O(n)
Method #5: Using Set Operations
Initialize the input list and the characters string.
Convert the characters string into a set for faster lookups.
Iterate through each tuple in the input list.
Convert each tuple into a set of characters.
Use the set intersection operation to find the common characters between the tuple and the characters string.
Check if the length of the intersection set is equal to the length of the tuple. If it is, then all the characters in the tuple are present in the characters string.
If step 6 is true, append the tuple to the result list.
Return the result list.
Python3
# Python3 code to demonstrate working of
# Filter Tuples with Strings of specific characters
# initializing lists
test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
# printing original lists
print("The original list is : " + str(test_list))
# initializing char_str
char_str = 'gfestb'
# converting char_str to a set
char_set = set(char_str)
# initializing result list
res = []
# iterating through each tuple in the input list
for tup in test_list:
# converting tuple to a set of characters
tup_set = set(''.join(tup))
# checking if all characters in the tuple are in char_set
if len(tup_set.intersection(char_set)) == len(tup_set):
res.append(tup)
# printing result
print("The filtered tuples : " + str(res))
OutputThe original list is : [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')]
The filtered tuples : [('gfg', 'best'), ('fest', 'gfg')]
Time complexity: O(n*m), where n is the number of tuples and m is the length of the longest tuple. In the worst case, we need to iterate through every character in every tuple.
Auxiliary space: O(m), where m is the length of the longest tuple. We need to create a set for each tuple.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read