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:
Python - Remove substring list from String
Next article icon

Python | Remove all strings from a list of tuples

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

Given a list of tuples, containing both integer and strings, the task is to remove all strings from list of tuples. 

Examples: 

Input : [(1, 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware')] Output :   [(1), (2), (3), (4)]  Input : [('string', 'Geeks'), (2, 225), (3, '111')] Output : [(), (2, 225), (3,)]

Method #1: Using filter() method 

Python3




# Python code to remove all strings from a list of tuples
 
# Check function to check isinstance
 
 
def check(x):
    return not isinstance(x, str)
 
 
# creating list of tuples
listOfTuples = [('string', 'Paras'), (2, 'Jain'), (3, 'GFG'),
                (4, 'Cyware'), (5, 'Noida')]
 
# using filter
output = ([tuple(filter(check, x)) for x in listOfTuples])
 
# printing output
print(output)
 
 
Output:
[(), (2,), (3,), (4,), (5,)]

Time complexity: O(n), where n is the number of tuples in the list. 
Auxiliary space: O(n), where n is the number of tuples in the list. 

Method #2: 

Python3




# Python code to remove all strings from a list of tuples
 
# Creating list of tuples
listOfTuples = [('string', 'Geeks'), (2, 225), (3, '111'),
                (4, 'Cyware'), (5, 'Noida')]
 
 
output = [tuple(j for j in i if not isinstance(j, str))
          for i in listOfTuples]
 
# printing output
print(output)
 
 
Output:
[(), (2, 225), (3,), (4,), (5,)]

Time complexity: O(n*m), where n is the number of tuples in the list and m is the maximum number of elements in a tuple.
Auxiliary space: O(n*m), as the output list stores all the tuples with non-string elements.

Method #3: Using type() method

STEPS:

  1. Create a list of tuples, listOfTuples, containing a mix of string and non-string elements.
  2. Create an empty list, x, to store the tuples containing only non-string elements.
  3. Iterate over each tuple in listOfTuples using a for loop.
  4. For each tuple, create an empty list, p, to store the non-string elements.
  5. Iterate over each element in the current tuple using a nested for loop.
  6. If the current element is not a string (determined using the type() function), append it to the p list.
  7. Convert the p list into a tuple using the tuple() function.
  8. Append the tuple containing only non-string elements to the x list.
  9. After all tuples have been processed, print the x list.

Python3




# Python code to remove all strings from a list of tuples
 
# creating list of tuples
listOfTuples = [('string', 'Paras'), (2, 'Jain'),
                (3, 'GFG'), (4, 'Cyware'), (5, 'Noida')]
x = []
for i in listOfTuples:
    p = []
    for j in i:
        if(not (type(j) is str)):
            p.append(j)
    p = tuple(p)
    x.append(p)
 
# printing output
print(x)
 
 
Output
[(), (2,), (3,), (4,), (5,)]

Method #4: Using inspect

To check if a variable is a string in Python, you can use the inspect module and the isclass function. Here is an example of how you can use this approach:

Python3




import inspect
 
def is_string(value):
    return inspect.isclass(type(value)) and issubclass(type(value), str)
 
# Test the function
print(is_string("hello"))  # Output: True
print(is_string(123))      # Output: False
print(is_string(True))     # Output: False
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
True False False

This approach will return True if the variable is a string, and False otherwise. It works by checking if the type of the variable is a class, and if that class is a subclass of the str class.

This approach can be used to remove all strings from a list of tuples by iterating through the list and filtering out the tuples that contain strings. Here is an example of how you could do this:

Python3




import inspect
 
def remove_strings_from_tuples(tuples):
    def is_string(value):
        return inspect.isclass(type(value)) and issubclass(type(value), str)
 
    return [tuple(value for value in t if not is_string(value)) for t in tuples]
 
tuples = [('string', 'Geeks'), (2, 225), (3, '111'), (4, 'Cyware'), (5, 'Noida')]
print(remove_strings_from_tuples(tuples))  # Output: [(), (2, 225), (3,), (4,), (5,)]
 
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
[(), (2, 225), (3,), (4,), (5,)]

Time complexity: O(n * m) where n is the number of tuples and m is the number of elements in each tuple. This is because the code needs to iterate through all tuples and all elements in each tuple to check if it is a string or not.
Auxiliary space: O(n * m) as well because the code creates a new list of tuples with the same number of tuples and elements as the original list of tuples.

Method #5: Using Regular expression method.

Algorithm:

  • Iterate over each tuple in the list of tuples.
  • For each tuple, iterate over each item in the tuple.
  • If the item is not a string, append it to a new list.
  • If the item is a string, use a regular expression to remove all characters in the string that are alphabetic characters.
  • Append the modified or unmodified item to the new list.
  • Convert the new list to a tuple and append it to the final list.
  • Return the final list of tuples.

Python3




import re
listOfTuples = [('string', 'Paras'), (2, 'Jain'), (3, 'GFG'), (4, 'Cyware'), (5, 'Noida')]
 
def remove_strings(tup):
    pattern = r'[a-zA-Z]+'
    result = []
    for item in tup:
        if not isinstance(item, str):
            result.append(item)
        else:
            result.append(re.sub(pattern,'', item))
            result.remove('')
    return tuple(result)
 
newList = [remove_strings(tup) for tup in listOfTuples]
print(newList)
#This code is contributed by tvsk
 
 
Output
[(), (2,), (3,), (4,), (5,)]

Time complexity:
The time complexity of this algorithm is O(n*m) where n is the number of tuples and m is the maximum length of a string in a tuple. This is because we need to iterate over each tuple and then iterate over each item in the tuple to check whether it is a string and perform the regular expression operation on it.

Auxiliary Space:
The auxiliary space of this algorithm is O(n*m) where n is the number of tuples and m is the maximum length of a string in a tuple. This is because we need to create a new list to store the modified or unmodified items for each tuple, and the length of each list is at most the length of the original tuple.

Method 5: Using a loop and isinstance() function:

Step-by-step approach:

  • Define an empty list to store the tuples without strings
  • Loop through each tuple in the list of tuples
  • Define an empty tuple to store the non-string values from the current tuple
  • Loop through each element in the current tuple
  • Check if the current element is a string using isinstance() function
  • If the element is not a string, append it to the empty tuple defined in step 3
  • After looping through all the elements in the current tuple, append the non-string tuple to the empty list defined in step 1
  • After looping through all the tuples in the list of tuples, print the final list of tuples without strings.

Below is the implementation of the above approach:

Python3




# Python code to remove all strings from a list of tuples
 
# Creating list of tuples
listOfTuples = [('string', 'Geeks'), (2, 225), (3, '111'),
                (4, 'Cyware'), (5, 'Noida')]
 
# Step 1
output = []
 
# Step 2
for tup in listOfTuples:
 
    # Step 3
    new_tup = ()
 
    # Step 4
    for ele in tup:
 
        # Step 5
        if not isinstance(ele, str):
 
            # Step 6
            new_tup += (ele,)
 
    # Step 7
    output.append(new_tup)
 
# Step 8
print(output)
 
 
Output
[(), (2, 225), (3,), (4,), (5,)]

Time complexity: O(n^2), where n is the total number of elements in the list of tuples. 
Auxiliary space: O(n), where n is the total number of elements in the list.

Method 6: Using heapq:

  1. Define an inner function is_string that takes a value as input and returns a boolean indicating whether the value is a string or not.
  2. Use a list comprehension to iterate through each tuple in tuples. For each tuple, create a new tuple by iterating through each value in the original tuple and selecting only the non-string values. The new tuple is added to a list of tuples that will be returned.
  3. Return the list of tuples.

Python3




import heapq
 
def remove_strings_from_tuples(tuples):
    def is_string(value):
        return isinstance(value, str)
 
    return [tuple(value for value in t if not is_string(value)) for t in tuples]
 
tuples = [('string', 'Geeks'), (2, 225), (3, '111'), (4, 'Cyware'), (5, 'Noida')]
print(remove_strings_from_tuples(tuples)) # Output: [(), (2, 225), (3,), (4,), (5,)]
#This code is contributed by Rayudu.
 
 
Output
[(), (2, 225), (3,), (4,), (5,)]

Time complexity:

The filter function iterates over the elements of each tuple in tuples, which takes O(nm) time, where n is the number of tuples in tuples and m is the maximum length of a tuple.
For each tuple, the filter function checks whether each element is a string, which takes O(m) time in the worst case.
The tuple function creates a new tuple from the filtered elements, which takes O(m) time in the worst case.
Therefore, the total time complexity of the function is O(nm^2).

Auxiliary Space:

The filter function returns an iterator that yields elements from the original tuple, so it does not create a new list or tuple. Therefore, the space complexity of the function is O(nm).
The tuple function creates a new tuple from the filtered elements, so it adds O(m) space complexity for each tuple in tuples.
Therefore, the total space complexity of the function is O(nm).



Next Article
Python - Remove substring list from String
author
everythingispossible
Improve
Article Tags :
  • Python
  • Python Programs
  • Python tuple-programs
  • python-tuple
Practice Tags :
  • python

Similar Reads

  • Python | Remove all digits from a list of strings
    The problem is about removing all numeric digits from each string in a given list of strings. We are provided with a list where each element is a string and the task is to remove any digits (0-9) from each string, leaving only the non-digit characters. In this article, we'll explore multiple methods
    4 min read
  • Python | Remove duplicate tuples from list of tuples
    Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x
    5 min read
  • Python | Remove prefix strings from list
    Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with a specific prefix are removed. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + remove() + startswith() The combinati
    5 min read
  • Python | Removing strings from tuple
    Sometimes we can come across the issue in which we receive data in form of tuple and we just want the numbers from it and wish to erase all the strings from them. This has a useful utility in Web-Development and Machine Learning as well. Let's discuss certain ways in which this particular task can b
    4 min read
  • Python - Remove substring list from String
    In Python Strings we encounter problems where we need to remove a substring from a string. However, in some cases, we need to handle a list of substrings to be removed, ensuring the string is adjusted accordingly. Using String Replace in a LoopThis method iterates through the list of substrings and
    3 min read
  • Python - Remove suffix from string list
    To remove a suffix from a list of strings, we identify and exclude elements that end with the specified suffix. This involves checking each string in the list and ensuring it doesn't have the unwanted suffix at the end, resulting in a list with only the desired elements. Using list comprehensionUsin
    3 min read
  • Python - Remove String from String List
    This particular article is indeed a very useful one for Machine Learning enthusiast as it solves a good problem for them. In Machine Learning we generally encounter this issue of getting a particular string in huge amount of data and handling that sometimes becomes a tedious task. Lets discuss certa
    4 min read
  • Remove Duplicate Strings from a List in Python
    Removing duplicates helps in reducing redundancy and improving data consistency. In this article, we will explore various ways to do this. set() method converts the list into a set, which automatically removes duplicates because sets do not allow duplicate values. [GFGTABS] Python a = ["Learn
    3 min read
  • Create a tuple from string and list - Python
    The task of creating a tuple from a string and a list in Python involves combining elements from both data types into a single tuple. The list elements are added as individual items and the string is treated as a single element within the tuple. For example, given a = ["gfg", "is"] and b = "best", t
    3 min read
  • Python | Remove Kth character from strings list
    Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
    7 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