siva
siva

Reputation: 2145

Remove empty element but keep zeros as values

I have a list as follows:

lst = [-1.33, '', -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, '',  1.37, 0]

where there are two empty elements '' in the list with several zeroes and float numbers.

How can I remove the empty elements but keep the zeroes? as follows...

lst2 = [-1.33, -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, 1.37, 0]   

I have tried the following:

lst2 = filter(None, lst)

and

lst2 = [x for x in lst if x if isinstance(x,str) == False]

but, it removes the zeroes as well.

I know floats return 12 decimal places, please ignore for example purposes.

Any advice? Thanks.

Upvotes: 2

Views: 1581

Answers (4)

Winston Ewert
Winston Ewert

Reputation: 45039

Let's take a look at what you have

lst2 = [x for x in lst 
if x 
if isinstance(x,str) == False]

What do you have the if x in there for?

Also, never never never use == False and == True

Use not isinstance(x, str)

So you should have

   lst2 = [x for x in lst if isinstance(x, str)]

Or as other have suggested

lst2 = [x for x in lst if x != '']

Since your list has both strings and numbers in it, I suspect that it'll be easier to deal this at the point that you created this list. Of course, without seeing that I can't be certain or tell you how to fix it.

Upvotes: 3

Sandro Munda
Sandro Munda

Reputation: 41030

I think that the filter function is the beautiful way to do what you want.

lst = [-1.33, '', -1.33, -1.33 -2.62, 0, -2.66, 1.41, 0, 0, 1.40, '',  1.37, 0]
lst2 = filter(lambda x: x != '', lst)
print lst2

Ouput:

[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.37, 1.37, 0]

As you can read here :

filter(function, iterable)

equals

[item for item in iterable if function(item)]

Upvotes: 1

Jochen Ritzel
Jochen Ritzel

Reputation: 107638

Why not simply remove all '' ?

>>> lst2 = [x for x in lst if x != '']
>>> lst2
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]
>>>

or you could keep only floats and ints:

>>> [x for x in lst if isinstance(x, (float, int))]
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]

# or a bit fancier
>>> import numbers
>>> [x for x in lst if isinstance(x, numbers.Number)]
[-1.33, -1.33, -3.95, 0, -2.66, 1.41, 0, 0, 1.4, 1.37, 0]

Upvotes: 9

N 1.1
N 1.1

Reputation: 12534

>>> l = [x for x in lst if x != '']
>>> l
[-1.3300000000000001, -1.3300000000000001, -3.9500000000000002, 0, -2.6600000000000001, 1.4099999999999999, 0, 0, 1.3999999999999999, 1.3700000000000001, 0]

Seems ok.

Upvotes: 2

Related Questions