Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Splitting String to List of Characters - Python
Next article icon

Python – Filter Tuples with Strings of specific characters

Last Updated : 24 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))
 
 
Output
The 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))
 
 
Output
The 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))
 
 
Output
The 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))
 
 
Output
The 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.



Next Article
Splitting String to List of Characters - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Filter String with substring at specific position
    Sometimes, while working with Python string lists, we can have a problem in which we need to extract only those lists that have a specific substring at a specific position. This kind of problem can come in data processing and web development domains. Let us discuss certain ways in which this task ca
    5 min read
  • Splitting String to List of Characters - Python
    We are given a string, and our task is to split it into a list where each element is an individual character. For example, if the input string is "hello", the output should be ['h', 'e', 'l', 'l', 'o']. Let's discuss various ways to do this in Python. Using list()The simplest way to split a string i
    2 min read
  • Splitting String to List of Characters - Python
    The task of splitting a string into a list of characters in Python involves breaking down a string into its individual components, where each character becomes an element in a list. For example, given the string s = "GeeksforGeeks", the task is to split the string, resulting in a list like this: ['G
    3 min read
  • Ways to split strings on Uppercase characters - Python
    Splitting strings on uppercase characters means dividing a string into parts whenever an uppercase letter is encountered. For example, given a string like "CamelCaseString", we may want to split it into ["Camel", "Case", "String"]. Let's discuss different ways to achieve this. Using Regular Expressi
    3 min read
  • Find the List elements starting with specific letter - Python
    The goal is to filter the elements of a list that start with a specific letter, such as 'P'. For example, in the list ['Python', 'Java', 'C++', 'PHP'], we aim to find the elements that begin with the letter 'P', resulting in the filtered list ['Python', 'PHP']. Let's explore different approaches to
    3 min read
  • Specific Characters Frequency in String List-Python
    The task of counting the frequency of specific characters in a string list in Python involves determining how often certain characters appear across all strings in a given list. For example, given a string list ["geeksforgeeks"] and a target list ['e', 'g'], the output would count how many times 'e'
    4 min read
  • Python - Extract Tuples with all Numeric Strings
    Given a list of tuples, extract only those tuples which have all numeric strings. Input : test_list = [("45", "86"), ("Gfg", "1"), ("98", "10")] Output : [('45', '86'), ('98', '10')] Explanation : Only number representing tuples are filtered. Input : test_list = [("Gfg", "1")] Output : [] Explanatio
    5 min read
  • Split String into List of characters in Python
    We are given a string and our task is to split this string into a list of its individual characters, this can happen when we want to analyze or manipulate each character separately. For example, if we have a string like this: 'gfg' then the output will be ['g', 'f', 'g']. Using ListThe simplest way
    2 min read
  • Python - Strings with all given List characters
    GIven Strings List and character list, extract all strings, having all characters from character list. Input : test_list = ["Geeks", "Gfg", "Geeksforgeeks", "free"], chr_list = [ 'f', 'r', 'e'] Output : ['free', "Geeksforgeeks"] Explanation : Only "free" and "Geeksforgeeks" contains all 'f', 'r' and
    4 min read
  • Python - Characters which Occur in More than K Strings
    Sometimes, while working with Python, we have a problem in which we compute how many characters are present in string. But sometimes, we can have a problem in which we need to get all characters that occur in atleast K Strings. Let's discuss certain ways in which this task can be performed. Method #
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences