Confused over Lists
Mark McEahern
marklists at mceahern.com
Fri Aug 2 10:14:48 EDT 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()
Short answer: Use filter.
Long answer: Experience the joy of Python's interactive nature...
$ python
Python 2.2.1 (#1, Jun 25 2002, 10:55:46)
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print filter.__doc__
filter(function or None, sequence) -> list, tuple, or string
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
>>> l2 = filter(lambda x: x % 2 == 0, l)
>>> l2
[0, 2, 4, 6, 8]
>>>
Questions?
Cheers,
// mark
-
More information about the Python-list
mailing list