Functional programming in Python cheatsheet

Map a function to a variable:

1
2
>>> (lambda x: x*2)(3)
6

iff shortcut in Python:

1
2
>>> (lambda x: "even" if x%2==0 else "odd")(5)
odd

or:

1
2
>>> (lambda x: x%2==0 and "even" or "odd")(5)
odd

Map a function to a list:

1
2
3
4
>>> map(lambda x: x*2, [1, 2, 3])
[1, 4, 6]
>>> [x*2 for x in [1, 2, 3]]
[1, 4, 6]

Filter a list:

1
2
3
4
>>> filter(lambda x: x % 2 == 1, [1, 2, 3])
[1, 3]
>>> [x for x in [1, 2, 3] if x % 2 ==1]
[1, 3]

Reduce a list:

1
2
>>> reduce(lambda x, y: x + y, [1, 2, 3])
6

Find maximum value in a list use key function:

1
2
>>> max([1, 2, 3], key=lambda x: x % 3)
2

Sort a list using key function:

1
2
>>> sorted([1, 2, 3], key=lambda x: x % 3)
[3, 1, 2]

More great functions can be found at the module itertools