Out[60]: False
The return object is a Boolean. Such a function can be applied to a whole list object by
using map:
In [ 61 ]: map(even, range( 10 ))
Out[61]: [True, False, True, False, True, False, True, False, True, False]
To this end, we can also provide a function definition directly as an argument to map, by
using lambda or anonymous functions:
In [ 62 ]: map(lambda x: x ** 2 , range( 10 ))
Out[62]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Functions can also be used to filter a list object. In the following example, the filter
returns elements of a list object that match the Boolean condition as defined by the even
function:
In [ 63 ]: filter(even, range( 15 ))
Out[63]: [0, 2, 4, 6, 8, 10, 12, 14]
Finally, reduce helps when we want to apply a function to all elements of a list object
that returns a single value only. An example is the cumulative sum of all elements in a
list object (assuming that summation is defined for the objects contained in the list):
In [ 64 ]: reduce(lambda x, y: x + y, range( 10 ))
Out[64]: 45
An alternative, nonfunctional implementation could look like the following:
In [ 65 ]: def cumsum(l):
total = 0
for elem in l:
total += elem
return total
cumsum(range( 10 ))
Out[65]: 45
LIST COMPREHENSIONS, FUNCTIONAL PROGRAMMING, ANONYMOUS FUNCTIONS
It can be considered good practice to avoid loops on the Python level as far as possible. list comprehensions and
functional programming tools like map, filter, and reduce provide means to write code without loops that is both
compact and in general more readable. lambda or anonymous functions are also powerful tools in this context.
Dicts
dict objects are dictionaries, and also mutable sequences, that allow data retrieval by keys
that can, for example, be string objects. They are so-called key-value stores. While list
objects are ordered and sortable, dict objects are unordered and unsortable. An example
best illustrates further differences to list objects. Curly brackets are what define dict
objects:
In [ 66 ]: d = {
‘Name’ : ‘Angela Merkel’,
‘Country’ : ‘Germany’,
‘Profession’ : ‘Chancelor’,
‘Age’ : 60
}
type(d)
Out[66]: dict
In [ 67 ]: print d[‘Name’], d[‘Age’]
Out[67]: Angela Merkel 60
Again, this class of objects has a number of built-in methods: