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.
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]