05python Comprehensions
05python Comprehensions
Comprehensions
Python’s higher-order
functions
• Python supports higher-order functions that
operate on lists similar to Scheme’s
>>> def square(x):
return x*x
>>> def even(x):
return 0 == x % 2
>>> map(square, range(10,20))
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
>>> filter(even, range(10,20))
[10, 12, 14, 16, 18]
>>> map(square, filter(even, range(10,20)))
[100, 144, 196, 256, 324]
>>> li = [3, 6, 2, 7, 1, 9]
>>> [elem*2 for elem in li if elem > 4]
[12, 14, 18]