Open In App

Python | Remove additional spaces in list

Last Updated : 14 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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 discuss certain ways in which this can be done. Method #1 : Using list comprehension + enumerate() In this method we create a whole new list rather than modifying the original one, and check for element and its preceding element for spaces and add only add one occurrence of space and leaving the rest. 

Output : 
The original list : ['GfG', '', '', '', '', 'is', '', '', 'best']
The list after removing additional spaces :  ['GfG', '', 'is', '', 'best']

Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.

  Method #2 : Using list comprehension + zip() + list slicing In this method, we take a pair at a time and check if it's both elements are empty, if so, we discard it. If anyone is empty or both are non-empty, we keep it in the list. 

Output : 
The original list : ['GfG', '', '', '', '', 'is', '', '', 'best']
The list after removing additional spaces :  ['GfG', '', 'is', '', 'best']

Time Complexity: O(n)

Auxiliary Space: O(n), where n is number of strings in list.


Next Article
Practice Tags :

Similar Reads