Skip to content

How to remove space in list Python | Example code

  • by

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.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *