list.remove() in a row

Asked

Viewed 117 times

0

have the list:

lista = ['', 'a', 'b', 'c', ' ', '', '', ' ']

and from her I’m trying to remove the blank items: [''] or [' '] then I have the following code:

if(ret_b == [' ']):
    ret_b.clear()

my doubt is: I can do this in a row?

2 answers

2

You can use the method filter and apply a lambda expression to remove whitespace and also empty strings:

lista = filter(lambda item: item != ' ' and item != '', lista)

Exit:

['a', b', 'c']

0


If you don’t mind generating a new list with the results, you can do:

>>> [elemento for elemento in lista if elemento.strip() != ""]
['a', 'b', 'c']

If you are sure that your list only contains strings (and remember that it is good practice not to mix different types in lists), then you can do it more simply:

>>> [elemento for elemento in lista if elemento.strip()]
['a', 'b', 'c']

This works because empty strings are evaluated as False when used in a context that asks for a boolean value. But, like other things that are not empty strings, they are also evaluated as False, only use if you are sure that all elements are strings.

  • The answer is correct, however unnecessary the part != "" in the expression if - empty strigns in Python already have false boolean valro, so it is only necessary: [elemento for elemento in lista if elemento.strip()] - if the method strip() return an empty strign, its boolean value is false, and the iffilter this element from the final list.

  • @jsbueno That’s what I said, Ué. :)

  • a is,in the second half of the reply. was even. Sorry. is that walking around answers not Pythonics around and got into the automatic mode of "commenting on the right way".

  • @jsbueno No problems. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.