How to remove space in list Python | Example code

The first way is using a replace() method with for-loop to remove space in list Python Another better way to achieve it is to use a list comprehension.

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)

Output:

How to remove space in list Python

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)

Output:

remove empty space element in list Python

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)

Output:

[‘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)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.