Mon 26 January 2015

Filed under Python


First: What is 'filter'?

In very short, filter runs the given function over the given iterable and only returns those that are true.

For example: We have a function that returns only those items in the list that are integers.

The Syntax

filter(function, iterable)

  • The function can be a function or a lambda expression.

  • The iterable can be any iterable - list, string, etc.

A few examples:

All these examples use this list: list = [1, 2, 3,"A", 11, "C", 12, 13, 14]

1. filter(lambda x: type(x) is str, list)

['A', 'C']

2. filter(lambda x: x<10, list)

[1, 2, 3]

3. filter(lambda x: type(x) is int, list)

[1, 2, 3, 11, 12, 13, 14]

4. filter(lambda x: type(x) is int and int(x)%2==0, list)

[2, 12, 14]

5. filter(lambda x: x%2==0, filter(lambda x: type(x) is int, list))

The inner filter returns all integers as a list. then the outer filter runs on that filtered list.

[2, 12, 14]

Comments © Dee Kras Powered by Pelican and Twitter Bootstrap. Icons by Font Awesome and Font Awesome More