Python - Merge consecutive empty Strings
Last Updated :
05 Mar, 2023
Sometimes, while working with python lists, we can have a problem in which we need to perform a merge operation on a string of lists. This merge is consecutive to convert multiple spaces to one. Let's discuss a certain way in which this can be performed.
Method #1 : Using loop, This is a brute way in which this task can be performed. In this, we find for empty strings using loop and ignore the consecutive strings in making of new list.
Python3
# Python3 code to demonstrate
# Merge consecutive empty Strings
# using loop
# Initializing list
test_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
# printing original list
print("The original list is : " + str(test_list))
# Merge consecutive empty Strings
# using loop
count = 0
res = []
for ele in test_list:
if ele =='':
count += 1
if (count % 2)== 0:
res.append('')
count = 0
else:
res.append(ele)
# printing result
print ("List after removal of consecutive empty strings : " + str(res))
Output : The original list is : ['Gfg', '', '', '', 'is', '', '', 'best', '']
List after removal of consecutive empty strings : ['Gfg', '', 'is', '', 'best', '']
Time Complexity: O(n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using List comprehension
In this method we use list comprehension and by just comparing we can merge consecutive empty strings.
Python3
# input list
test_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
print("The original list is : " + str(test_list))
# list comprehension
res= [test_list[i] for i in range(len(test_list)-1) if test_list[i]!=test_list[i+1]]
# appending last word in the list because we are checking upto n-1
res.append(test_list[-1])
print ("List after removal of consecutive empty strings : " + str(res))
# this code is contributed Asif_shaik
OutputThe original list is : ['Gfg', '', '', '', 'is', '', '', 'best', '']
List after removal of consecutive empty strings : ['Gfg', '', 'is', '', 'best', '']
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #3 : Using filter() function :
Python3
# Initialize input list
input_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
# Use filter function to filter out empty strings
output_list = list(filter(lambda x: x != "", input_list))
# Print the output list
print(output_list)
#This code is contributed by pinjala Jyothi.
Output['Gfg', 'is', 'best']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using join() and split()
Python3
# Initializing list
test_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
# printing original list
print ("The original list is : " + str(test_list))
# Using join() and split()
res = ' '.join(test_list).split()
# printing result
print ("List after removal of consecutive empty strings : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : ['Gfg', '', '', '', 'is', '', '', 'best', '']
List after removal of consecutive empty strings : ['Gfg', 'is', 'best']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Using a lambda function and the reduce() method:
Algorithm:
- Import the reduce function from the functools module.
- Initialize the test_list with a list of strings containing empty strings in between some non-empty strings.
- Print the original test_list.
- Use the reduce function to filter out empty strings from the test_list.
- Define a lambda function to reduce the list to a new list, only if the element is not an empty string.
- The reduce function applies the lambda function to each element of the list in turn, and the output of the previous step is used as the input to the next step.
- Finally, the result of the reduce function is printed as the new list containing only non-empty strings.
Python3
from functools import reduce
# Initializing list
test_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
# printing original list
print ("The original list is : " + str(test_list))
# Using join() and split()
res = reduce(lambda x, y: x + [y] if y != '' else x, test_list, [])
# printing result
print ("List after removal of consecutive empty strings : " + str(res))
#This code is contributed by tvsk.
OutputThe original list is : ['Gfg', '', '', '', 'is', '', '', 'best', '']
List after removal of consecutive empty strings : ['Gfg', 'is', 'best']
Time complexity: The time complexity of this code is O(n), where n is the length of the input list. The join() and split() methods used in the alternative solution have a time complexity of O(n), so the reduce() method has a similar time complexity of O(n).
Auxiliary space complexity: The auxiliary space complexity of this code is O(n), where n is the length of the input list. The reduce() function uses an empty list to store the output of each iteration, which can have a maximum length of n.
Method #6: Using Enumeration
Algorithm:
- Initialize an empty list to store the result.
- Iterate through the list using enumerate(), with index i and word as the value.
- Check if the index is 0 or the previous element is not equal to the current element.
- If the condition is satisfied, append the word to the result list.
- Return the result list.
Python3
#input list
test_list = ['Gfg', '', '', '', 'is', '', '', 'best', '']
print("The original list is : " + str(test_list))
#using enumeration
res = [word for i, word in enumerate(test_list) if i == 0 or test_list[i-1] != word]
print ("List after removal of consecutive empty strings : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original list is : ['Gfg', '', '', '', 'is', '', '', 'best', '']
List after removal of consecutive empty strings : ['Gfg', '', 'is', '', 'best', '']
The time complexity is O(n), where n is the length of the input list. This is because the code iterates through the entire list exactly once to remove the consecutive empty strings. The time taken by the code is directly proportional to the length of the list.
The auxiliary space is O(n). This is because the code creates a new list to store the result, which can be at most the same size as the input list. Therefore, the space taken by the code is directly proportional to the length of the list.
Similar Reads
Python - Consecutive element deletion strings
Sometimes, while working with Python, we can have a problem in which we have a string and wish to extract all possible combination of words after deletion of consecutive elements one at a time. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
6 min read
Python | Consecutive element swapping in String
Sometimes, while working with strings, we can have a problem in which we may require to perform swapping of consecutive elements in string. Let's discuss certain ways in which this task can be performed. Method #1 : Using join() + zip() + generator expression The combination of above functions can b
3 min read
Python - Convert None to empty string
In Python, it's common to encounter None values in variables or expressions. In this article, we will explore various methods to convert None into an empty string.Using Ternary Conditional OperatorThe ternary conditional operator in Python provides a concise way to perform conditional operations wit
2 min read
Empty String to None Conversion - Python
We are given a empty string we need to convert string to None. For example s = "" we are given a string we need to convert that to None so that out output becomes None.Using TernaryTernary operator in Python allows us to perform conditional expressions in a single line. We can use it to convert an e
3 min read
Python | Consecutive String Comparison
Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it's next element in a list and return all strings whose next element is similar list. Let's discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop
3 min read
Python - String Matrix Concatenation
Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + join() We can solve this problem using lis
4 min read
Find Longest Consecutive Letter and Digit Substring - Python
The task is to identify the longest sequence of consecutive letters or digits in a given string. A consecutive letter or digit refers to a substring where each character is adjacent to the next one in the alphabet for letters or numerically for digits. It involves identifying the longest sequence of
4 min read
Python - Equidistant consecutive characters Strings
Given a Strings List, extract all the strings, whose consecutive characters are at the common difference in ASCII order. Input : test_list = ["abcd", "egil", "mpsv", "abd"] Output : ['abcd', 'mpsv'] Explanation : In mpsv, consecutive characters are at distance 3. Input : test_list = ["abcd", "egil",
9 min read
Check if String is Empty or Not - Python
We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example:Using Comparison Operator(==)The si
2 min read
Python | Ways to merge strings into list
Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requir
4 min read