remove all elements in a list with a particular value

John Zenger johnzenger at gmail.com
Wed May 16 11:41:08 EDT 2007


On May 16, 11:21 am, Lisa <lisa.engb... at gmail.com> wrote:
> I am reading in data from a text file.  I want to enter each value on
> the line into a list and retain the order of the elements.  The number
> of elements and spacing between them varies, but a typical line looks
> like:
>
> '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10      3.0   '
>
> Why does the following not work:
>
> line = '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10      3.0   '
> li = line.split(' ')
> for j,i in enumerate(li):
>         if i == '':
>                 li.remove(i)
>
> After the original split I get:
> ['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '',
> '340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', '']
>
> And after the for loop I get:
> ['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '', '', '',
> '3.0', '', '', '']
>
> It doesn't remove all of the empty elements.  Is there a better way to
> split the original string?  Or a way to catch all of the empty
> elements?
>
> Thanks

As explained elsewhere, this is not the best way to do a split.  But
if in the future you run into the problem of how to remove all
elements in a list with a particular value, here are two popular
approaches:

>>> items =  ['', '', '', 'SRCPARAM', '', '', '1', '6.35e-07', '15.00', '',
'340.00', '', '', '1.10', '', '', '', '', '', '3.0', '', '', '']
>>> print filter(lambda i: i != '', items)
['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0']
>>> print [x for x in items if x != '']
['SRCPARAM', '1', '6.35e-07', '15.00', '340.00', '1.10', '3.0']




More information about the Python-list mailing list