Functions

Default Arguments

Default arguments for functions are arguments that are used when the user does not provide them.

A function can take optional parameters, which are passed as labeled values. Optional parameters must be placed at the end of the function declaration.

Python functions don’t require a return statement. If there is no return statement, the function returns None.

A variable can be assigned to a function.

Lambda Functions

Examples

>>> my_func = lambda n:n + 1
>>> my_func(2)
3
'''

Using a lambda to select a key when sorting a list:

>>> games_won = [('julian', 3), ('bob', 1), ('jim', 1), ('sara', 0), ('tim', 5)]
>>> sorted(games_won)
[('bob', 1), ('jim', 1), ('julian', 3), ('sara', 0), ('tim', 5)]
>>> sorted(games_won, key=lambda n:n[1])
[('sara', 0), ('bob', 1), ('jim', 1), ('julian', 3), ('tim', 5)]
>>>

Convert def split_title_and_name() to a lambda.

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']

def split_title_and_name(person):
    return person.split()[0] + ' ' + person.split()[-1]

#option 1
for person in people:
    print(split_title_and_name(person) == (lambda x: x.split()[0] + ' ' + x.split()[-1])(person))

#option 2
list(map(split_title_and_name, people)) == list(map(lambda person: person.split()[0] + ' ' + person.split()[-1], people))

So, this function:

def split_title_and_name(person):
    return person.split()[0] + ' ' + person.split()[-1]

is the same as this:

lambda x: x.split()[0] + ' ' + x.split()[-1])(person)

Example of a lambda definition, and an argument passed to it, at the same time:

print((lambda x: x + 2)(3))
5

map()

Map applies a function (first parameter) to one or more iterables (second parameter & up) and returns an iterable (map object) of the results.

Examples store1 and store2 are lists of prices at each store for the same set of items. Find the lower price for each item.

store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
cheapest
<map at 0x7f87dc0462b0>

for item in cheapest:
    print(item)

9.0     # lowest price for 1st item = store2 price.
11.0    # lowest price for 2nd item = store1 price.
12.34   # etc...
2.01