list.remove () in a row

0

I have the list:

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

And I'm trying to remove the blank items: [''] or [' '] soon I have the following code:

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

My question is: Can I do this in a row?

    
asked by anonymous 26.07.2016 / 17:53

2 answers

0

If you do not mind generating a new list of results, you can do the following:

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

In case you are sure that your list only contains strings (and it is worth remembering that it is good practice not to mix different types in lists), then you can do it in a simpler way:

>>> [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 since other things that are not empty strings are also evaluated as False , only use if you are sure that all elements are strings.

    
26.07.2016 / 18:04
2

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

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

Output:

  

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

    
26.07.2016 / 18:04