How to del item of a list in loop?

John Machin sjmachin at lexicon.net
Sun Jan 16 02:01:00 EST 2005


Bengt Richter wrote:
> No one seems to have suggested this in-place way yet,
> so I'll trot it out once again ;-)
>
>  >>> lst = [1, 2, 3]
>  >>> i = 0
>  >>> for item in lst:
>  ...    if item !=2:
>  ...        lst[i] = item
>  ...        i += 1
>  ...
>  >>> del lst[i:]
>  >>> lst
>  [1, 3]

Works, but slowly. Here's another that appears to be the best on large
lists, at least for removing 1 element. It's O(len(list) *
number_to_be_removed).

!def method_try_remove(lst, remove_this):
!    try:
!        while 1:
!            lst.remove(remove_this)
!    except:
!        pass




More information about the Python-list mailing list