SoFunction
Updated on 2024-10-30

A summary of python's method for removing all blank entries from a list.

First, let's write a random list with spaces:

list1 = ['122','2333','3444',' ','422',' ',' ','54',' ']

I'm sure someone has already tried, such as the following to remove spaces, for example:

# -*- coding:utf-8 -*-
for i in list1:
 if i == ' ':
 (' ')
print list1

But the result you'll find is this, it always fails to delete the space completely, leaving one at the end.

Method I:

At this point, try changing '==' to in.

# -*- coding:utf-8 -*-
for i in list1:
 if ' ' in list1:
 (' ')
print list1

I've seen the way to use ''join'' online before, the link can't be found, this method it does delete empty strings with one length ' ', but it's ok for more regular intervals, not so friendly for irregular intervals, and it generates 0 length regardless of the regularity of intervals '' empty string.

Method II:

Method one is later to write this article when testing the article at the very beginning of the wrong way to write, because I do not remember too well, inadvertently thought of in, it turned out that the results are right, I myself first thought of the method is like this, the first to get the number of spaces, and then traversed, one by one to delete:

for i in range((' ')):
 (' ')

Method Three:

Then after using for I wondered if I could use while, and how to write while, and tested it and found that I could:

while ' ' in list1:
 (' ')
print list1

The above was written relatively early, using mostly removes, and now that I've learned some optimizations, and then added the hints in the comments, I've realized that derivatives work, thanks for that!

This summary of python's method for removing all space items from a list is all I have to share with you.