Confused over Lists

Yigal Duppen yduppen at xs4all.nl
Fri Aug 2 16:41:55 CEST 2002


> If I have a list of items, and wish to test each item, and remove those
> items that meet a certain criteria, I assumed I could use list.remove()
> 
> however I came across the following problem:
[snip]

Well, I don't know how iteration on lists really works, but in this specific 
case there are two much better alternatives.

1) Use 'filter'.
2) Use list comprehensions.

filter(func, list)
Filter returns a new consisting of all elements i in list for which func(i) 
is true.
In your specific example, that would be:

>>> def isNotOne(n):
...     return n != 1
...
>>> a_list = [1, 1, 2, 3, 1, 4]
>>> filter(isNotOne, a_list)
[2, 3, 4]

Or if you like lambda:
>>> filter(lambda n: n != 1, a_list)
[2, 3, 4]


List comprehensions can do the same, but they aren't available in older 
versions of Python. List comprehensions look as follows:
[ expression *for* variable *in* sequence *if* test ]
where *for*, *in* and *if* represent the keywords for, in and if resp.

In your case this would become:
>>> [ n
...   for n in a_list
...   if n != 1
... ]
[2, 3, 4]


Both filter and list comprehensions are usually much faster and less 
error-prone than looping and copying yourself.

YDD
-- 
.sigmentation fault



More information about the Python-list mailing list