Python - Remove Punctuation Tuples
Last Updated :
15 Mar, 2023
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the removal of all the tuples which contain punctuation in tuples. This kind of problem can occur in data filtering applications. Let's discuss certain ways in which this task can be performed.
Input : test_list = [('.', ', '), ('!', 8)] Output : [] Input : test_list = [(1, 3), (3, 8)] Output : [(1, 3), (3, 8)]
Method #1 : Using any() + list comprehension + string.punctuation The combination of above functions can be used to solve this problem. In this, we perform the task of identifying punctuation using string.punctuations, and any() is used to test if the elements belong to any of punctuation.
Python3
# Python3 code to demonstrate working of
# Remove Punctuation Tuples
# Using any() + list comprehension + string.punctuation
import string
# initializing list
test_list = [('.', ', '), ('!', 8), (5, 6), (';', 10)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Punctuation Tuples
# Using any() + list comprehension + string.punctuation
res = [idx for idx in test_list if not any(punc in idx for punc in string.punctuation)]
# printing result
print("Tuples after punctuation removal : " + str(res))
OutputThe original list is : [('.', ', '), ('!', 8), (5, 6), (';', 10)]
Tuples after punctuation removal : [(5, 6)]
Method #2 : Using regex() + filter() + lambda + string.punctuation The combination of above functions can be used to solve this problem. In this, we perform the task of identification of punctuations using regex expressions and filtering using filter() + lambda. Has limitation of working only on strings and for checking on particular index.
Python3
# Python3 code to demonstrate working of
# Remove Punctuation Tuples
# Using regex() + filter() + lambda + string.punctuation
import string
import re
# initializing list
test_list = [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
# printing original list
print("The original list is : " + str(test_list))
# Remove Punctuation Tuples
# Using regex() + filter() + lambda + string.punctuation
temp = re.compile('[{}]'.format(re.escape(string.punctuation)))
res = list(filter(lambda tup: not temp.search(tup[0]), test_list))
# printing result
print("Tuples after punctuation removal : " + str(res))
OutputThe original list is : [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
Tuples after punctuation removal : [('5', '6')]
Method #3 : Using any()+isinstance()
Approach/Intuition :
The approach is to iterate through each tuple in the input list and check if any element in the tuple is a string containing punctuation marks. If such an element is found, the current tuple is skipped. Otherwise, the current tuple is added to a new list which will contain tuples without any punctuation marks. The resulting list is returned.
Steps were to implement above approach :
- Create an empty list to store tuples without punctuation marks.
- Loop over each tuple in the input list.
- Check if any element in the current tuple is a string containing punctuation marks.
- If a string with punctuation marks is found, skip the current tuple.
- Otherwise, add the current tuple to the list of tuples without punctuation marks.
- Return the resulting list.
Python3
# Python3 code to demonstrate working of
# Remove Punctuation Tuples
# Using regex() + filter() + lambda + string.punctuation
def remove_punctuation_tuples(test_list):
# Create a list to store tuples that do not contain punctuation marks
filtered_list = []
# Loop over each tuple in the input list
for tpl in test_list:
# Check if any element in the tuple is a string containing punctuation marks
if any(isinstance(elem, str) and any(char in elem for char in '.,?!:;') for elem in tpl):
continue # skip this tuple
else:
filtered_list.append(tpl) # add this tuple to the filtered list
return filtered_list
# Test the function with the given inputs
test_list = [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
# printing original list
print("The original list is : " + str(test_list))
res = remove_punctuation_tuples(test_list)
# printing result
print("Tuples after punctuation removal : " + str(res))
OutputThe original list is : [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
Tuples after punctuation removal : [('5', '6')]
Time Complexity: O(n*m), The time complexity of the function depends on the size of the input list and the size of the tuples in the list. Since we iterate over each tuple and then each element in each tuple, the time complexity is O(n*m), where n is the number of tuples in the input list and m is the maximum number of elements in a tuple.
Space complexity: O(n), The space complexity of the function depends on the size of the input list and the number of tuples without punctuation marks. We create a new list to store the filtered tuples, so the space complexity is also O(n), where n is the number of tuples in the input list.
Method #4: Using a for loop and string.punctuation.translate():
Algorithm :
1.Import the string module to access the punctuation characters.
2.Use the str.maketrans() method to create a translator that removes all punctuation characters.
3.Initialize the original list of tuples.
4.Initialize an empty result list to hold the filtered tuples.
5.Loop through each tuple in the original list.
6.Use the translator to remove the punctuation from the first element of the tuple.
7.Check if the first element of the tuple is non-empty.
8.If the first element is non-empty, add the tuple to the result list.
9.Print the result list.
Python3
import string
translator = str.maketrans('', '', string.punctuation)
test_list = [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
# printing original list
print("The original list is : " + str(test_list))
res = []
for tup in test_list:
if not any(char in string.punctuation for char in tup):
res.append(tup)
print("Tuples after punctuation removal : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original list is : [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
Tuples after punctuation removal : [('5', '6')]
The time complexity : O(N), where N is the length of the input list test_list.
The space complexity : O(N), since the resulting list res will have at most N elements in it.
Method #5: Using list comprehension and string.punctuation with reduce():
1.Import the required modules - string module for the list of punctuation marks, reduce function from functools module to perform a logical and operation on a list of boolean values.
2.Initialize the given list of tuples as test_list.
3.Print the original list using print() function and str() method to convert the list to a string.
4.Get the list of all punctuation marks using string.punctuation and store it in punctuation.
5.Use a list comprehension to filter out the tuples that have a punctuation mark in the first element of the tuple.
6.For each tuple in the test_list, use the reduce() function to perform a logical and operation on a list of boolean values.
7.The list of boolean values is obtained by iterating over each character in the first element of the tuple and checking if the character is not a punctuation mark.
8.The reduce() function returns a single boolean value which indicates whether all the characters in the first element of the tuple are not punctuation marks. If the value is True, the tuple is included in the resulting list.
The resulting list is stored in res.
9.Print the resulting list using print() function and str() method to convert the list to a string.
Python3
import string
from functools import reduce
# initializing list
test_list = [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
# printing original list
print("The original list is : " + str(test_list))
punctuation = string.punctuation
res = [tup for tup in test_list if reduce(lambda a, b: a and b, [c not in punctuation for c in tup[0]])]
print("Tuples after punctuation removal : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original list is : [('.', ', '), ('!', '8'), ('5', '6'), (';', '10')]
Tuples after punctuation removal : [('5', '6')]
The time complexity : O(n*m), where n is the number of tuples in the input list and m is the average length of the strings in the tuples. This is because we need to iterate over each tuple and perform a reduce operation that checks each character in the first element of the tuple.
The space complexity: O(n), where n is the number of tuples in the input list. This is because we are creating a new list to store the filtered tuples, which will have the same length as the input list in the worst case. Additionally, we are using a constant amount of extra space for the punctuation variable and the res variable.
Similar Reads
Python | Remove matching tuples
The problem of removing the matching elements from two lists and constructing a new list having just the filtered elements not present in 2nd list has been discussed earlier, but sometimes, we have more than an elementary element, but a tuple as element of list. Handling such a case requires differe
6 min read
Python - Remove Punctuation from String
In this article, we will explore various methods to Remove Punctuations from a string.Using str.translate() with str.maketrans()str.translate() method combined with is str.maketrans() one of the fastest ways to remove punctuation from a string because it works directly with string translation tables
2 min read
Python - Remove Tuples of Length K
Given list of tuples, remove all the tuples with length K. Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2 Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] Explanation : (4, 5) of len = 2 is removed. Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K =
6 min read
Python | Replace punctuations with K
Sometimes, while working with Python Strings, we have a problem in which we need to perform the replacement of punctuations in String with specific characters. This can have applications in many domains such as day-day programming. Let's discuss certain ways in which this task can be performed. Meth
7 min read
Python | Removing duplicates from tuple
Many times, while working with Python tuples, we can have a problem removing duplicates. This is a very common problem and can occur in any form of programming setup, be it regular programming or web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using set()
4 min read
Python | Replace duplicates in tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to remove tuples elements that occur more than one times and replace duplicas with some custom value. Let's discuss certain ways in which this task can be performed. Method #1 : Using set() + list comprehension The c
5 min read
Python - Reverse String except punctuations
Given a string with punctuations, perform string reverse, leaving punctuations at their places. Input : test_str = 'geeks@#for&%%gee)ks' Output : skeeg@#rof&%%ske)eg Explanation : Whole string is reversed, except the punctuations. Input : test_str = 'geeks@#for&%%gee)ks' [ only substring
5 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 additional spaces in list
Sometimes, we have a list that contains strings and spaces in between them. We desire to have uniformity, so that later if we decide them, we just have single spaces between the lists. Hence its sometimes necessary to remove the additional unnecessary spaces between the words in a list. Let's discus
3 min read
Python - Triple quote String concatenation
Sometimes, while working with Python Strings, we can have a problem in which we need to perform concatenation of Strings which are constructed by Triple quotes. This happens in cases we have multiline strings. This can have applications in many domains. Let us discuss certain ways in which this task
4 min read