Example remove space in list Python
Simple example code:
Replace + Append method with for loop
It will remove space not empty string.
list1 = ['A', ' ', ' ', 'B', ' ', 'C'] res =  for ele in list1: j = ele.replace(' ', '') res.append(j) print(res)
Another way using loop + strip()
It will remove empty items from the list.
list1 = ['A', ' ', ' ', 'B', ' ', 'C'] res =  for ele in list1: if ele.strip(): res.append(ele) print(res)
Best way list comprehension + strip()
One-liner approach to perform this task instead of using a loop.
list1 = ['A', ' ', ' ', 'B', ' ', 'C'] remove_space = [x.strip(' ') for x in list1] print(remove_space) delete_empty = [ele for ele in list1 if ele.strip()] print(delete_empty)
[‘A’, ”, ”, ‘B’, ”, ‘C’]
[‘A’, ‘B’, ‘C’]
Do comment if you have any doubts and suggestions on this Python list code.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.