how to remove 50000 elements from a 100000 list?

Diez B. Roggisch deets at nospam.web.de
Fri May 5 09:52:42 EDT 2006


Ju Hui wrote:

> I want to remove about 50000 elements from a list,which has 100000
> elements.
> sample code like below:
> 
>>>> a=range(10)
>>>> b=range(4)
>>>> for x in b:
> ...     a.remove(x)
> ...
>>>> a
> [4, 5, 6, 7, 8, 9]
> 
> when a and b is small size, it will finished quickly, but when a and b
> have many elements.
> such as:
>>>> a=range(100000)
>>>> b=range(50000)
>>>> for x in b:
> ...     a.remove(x)
> ...
> it will very slowly. Shall I change to another data structure and choos
> a better arithmetic?


How about a listcomprehension? 


new_list = [e for e in old_list if predicate(e)]
# Possibly you need this, too:
old_list[:] = new_list


Diez



More information about the Python-list mailing list