How to del item of a list in loop?

John Machin sjmachin at lexicon.net
Sat Jan 15 19:42:55 EST 2005


Nick Coghlan wrote:
>
> I think this is about the best you can do for an in-place version:
>    for i, x in enumerate(reversed(lst)):
>      if x == 2:
>        del lst[-i]

Don't think, implement and measure. You may be surprised. Compare these
two for example:

!def method_del_bkwds(lst, x):
!    for inx in xrange(len(lst) - 1, -1, -1):
!        if lst[inx] == x:
!            del lst[inx]
!    return lst

!def method_coghlan(lst, x):
!    for i, obj in enumerate(reversed(lst)):
!        if obj == x:
!            del lst[-i]
!    return lst

>
> The effbot's version is still going to be faster though:
>    lst = [x for x in lst if x != 2]

Have you measured this?




More information about the Python-list mailing list