{article Dive into Python}{title} {text}{/article}

A filter expression can be any expression that evaluates true or false. Any element for which the filter epxression evaluates true will be included in the mapping.

>>> li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
>>> li
['a', 'mpilgrim', 'foo', 'b', 'c', 'b', 'd', 'd']
>>> [elem for elem in li if len(elem) > 1]
['mpilgrim', 'foo']
>>> [elem for elem in li if elem != "b"]
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
>>> [elem for elem in li if li.count(elem) == 1]
['a', 'mpilgrim', 'foo', 'c']
>>> [elem for elem in li if li.count(elem) == 2]
['b', 'b', 'd', 'd']
>>>

The mapping expression here is simple (it just returns the value of each element), so concentrate on the filter expression. As Python loops through the list, it runs each element through the filter expression. If the filter expression is true, the element is mapped and the result of the mapping expression is included in the returned list.

Here, you are filtering out all the one−character strings, so you're left with a list of all the longer strings. Here, you are filtering out a specific value, b. Note that this filters all occurrences of b, since each time it comes up, the filter expression will be false.


count is a list method that returns the number of times a value occurs in a list. You might think that this filter would eliminate duplicates from a list, returning a list containing only one copy of each value in the original list. But it doesn't, because values that appear twice in the original list (in this case, b and d) are excluded completely. There are ways of eliminating duplicates from a list, but filtering is not the solution.