4
filter(function,  an_iter)
*If the iterable an_iter is a sequence, then the returned value is of that same type, 
otherwise the returned value is a list.* 

I came across the above description as part of the definition for the filter(func, a_sequence) function in Python.

I understand how filter works on a sequence type (lists, strings, tuples). However, can you give me situations where a non-sequence type is the an_iter parameter and what kind of result would form?

0

3 Answers 3

5

When it says 'non-sequence', it basically means generators or unordered iterables. Here is an example with xrange:

>>> filter(lambda n: n % 2, xrange(10))
[1, 3, 5, 7, 9]

And with a set:

>>> filter(lambda n: n % 2, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
[1, 3, 5, 7, 9]
Sign up to request clarification or add additional context in comments.

2 Comments

Not entirely. filter(lambda x: x%2, {1,2,3,4,5}) gives back a list because sets are not sequences. Similarly for dicts.
For python3, it has changed.
5

For python 3, the definition is changed.

From doc

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Example:

>>> filter(lambda x: x in 'hello buddy!', 'hello world')
<filter object at 0x000002ACBEEDCB00> # filter returns object !important

>>> ''.join([i for i in filter(lambda x: x in 'hello buddy!', 'hello world')])
'hello old'

>>> [i for i in filter(lambda n: n % 2, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9})]
[1, 3, 5, 7, 9]

Comments

0

It may help to see the effective implementation of filter:

def filtered(function, iterable):
    if function is None:
        return (item for item in iterable if item)
    return (item for item in iterable if function(item))

Another way to implement it (with the same result) is:

def filtered(function, iterable):
    if function is None:
        function = bool
    return (item for item in iterable if function(item))

The result always is iterable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.