Reputation: 1093
Generally you think of applying one function to a list of values, thereby creating a new list (the associated Python function is map
). However, what if you apply a list of functions to one value, thereby creating a new value? For example:
allCaps = lambda s: s.upper()
exclaim = lambda s: s + '!'
quote = lambda s: '"' + s + '"'
funcs = [allCaps, exclaim, quote]
value = 'hello'
for f in funcs:
value = f(value)
print(value) # "HELLO!"
Is there a name for this sort of operation (similar to map, filter, reduce)?
Upvotes: 1
Views: 65
Reputation: 250961
You can use reduce()
for this, just pass 'hello' as the initial(reduce(function, sequence[, initial])
) value.:
>>> reduce(lambda x, y: y(x), funcs, 'hello')
'"HELLO!"'
Upvotes: 3