Sub topic 1
Functions are values: passing and returning them
Prerequisites
You should know how to define and call functions with def, use lists, tuples, and dictionaries, write list comprehensions, and use function arguments such as default values, *args, and **kwargs.
Functions are values
In Python, a function is an object. You can store it in a variable, put it in a list, pass it to another function, or return it from a function. A function that accepts or returns another function is called a higher-order function.
def double(number):
return number * 2
operation = double
print(operation(5)) # 10
def apply(operation, value):
return operation(value)
print(apply(double, 7)) # 14operation and double refer to the same function. Passing double uses the function itself. Passing double() would call it immediately and pass its result instead.
Writing a lambda expression
A lambda is a small anonymous function. Its syntax is lambda parameters: expression. The expression is returned automatically.
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
by_count = lambda pair: pair[1]
print(by_count(pairs[0])) # 3Use a lambda when the operation is short and needed in one place. The following lambda accepts one argument and returns its second item.
What a lambda cannot do
A lambda can contain only one expression. It cannot contain statements such as return, for, while, assignment, or try. Conditional expressions are allowed, but complex logic usually belongs in a named def function.
Sorting and ranking with key functions
A key function maps each item to the value used for comparison. sorted, min, and max accept a key argument.
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=lambda pair: pair[1]))
# [('pear', 1), ('fig', 2), ('apple', 3)]
print(max(pairs, key=lambda pair: pair[1]))
# ('apple', 3)The original tuples remain unchanged. Python calls the key function for each item, then orders or selects items using the returned values.
Exercise
What does sorted(["pear", "fig", "apple"], key=lambda word: len(word)) return?
Show answer
['fig', 'pear', 'apple'], ordered by each string's length.