remove all elements in a list with a particular value

MRAB google at mrabarnett.plus.com
Thu May 17 16:56:55 EDT 2007


On May 16, 4:21 pm, 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)
>
[snip]
What you're forgetting is that when you remove an item from a list all
the following items move down.

If you try this:

li = list('abc')
for i, j in enumerate(li):
    print ", ".join("li[%d] is '%s'" % (p, q) for p, q in
enumerate(li))
    print "Testing li[%d], which is '%s'" % (i, j)
    if j == 'a':
        print "Removing '%s' from li" % j
        li.remove(j)

then you'll get:

li[0] is 'a', li[1] is 'b', li[2] is 'c'
Testing li[0], which is 'a'
Removing 'a' from li
li[0] is 'b', li[1] is 'c'
Testing li[1], which is 'c'

You can see that when 'enumerate' yielded li[0] 'b' was in li[1] and
when it yielded li[1] 'b' was in li[1]; it never saw 'b' because 'b'
moved!

Oops! Been there, done that... :-)




More information about the Python-list mailing list