Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

7.1.3 Functional Programming Tools

There are three built-in functions that are very useful when used with lists: filter(), map(), and reduce().

‘filter(function, sequence)’ returns a sequence (of the same type, if possible) consisting of those items from the sequence for which function(item) is true. For example, to compute some primes:

    >>> def f(x): return x % 2 != 0 and x % 3 != 0
    ...
    >>> filter(f, range(2, 25))
    [5, 7, 11, 13, 17, 19, 23]

‘map(function, sequence)’ calls function(item) for each of the items in the sequence and returns a list of the return values. For example, to compute some cubes:

    >>> def cube(x): return x*x*x
    ...
    >>> map(cube, range(1, 11))
    [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence (or None if some sequence is shorter than another). If None is passed for the function, a function returning its argument(s) is substituted.

Combining these two special cases, we see that ‘map(None, list1, list2)’ is a convenient way of turning a pair of lists into a list of pairs. For example:

    >>> seq = range(8)
    >>> def square(x): return x*x
    ...
    >>> map(None, seq, map(square, seq))
    [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25),
    (6, 36), (7, 49)]

‘reduce(func, sequence)’ returns a single value constructed by calling the binary function func on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:

    >>> def add(x,y): return x+y
    ...
    >>> reduce(add, range(1, 11))
    55

If there's only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.

A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on. For example,

    >>> def sum(seq):
    ...     def add(x,y): return x+y
    ...     return reduce(add, seq, 0)
    ... 
    >>> sum(range(1, 11))
    55
    >>> sum([])
    0

 
 
  Published under the terms of the Python License Design by Interspire