Open In App

Python | Remove all strings from a list of tuples

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
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).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads