def add_one(x):
return x+1
10)
add_one(
# now assign this function to another, Add_One
= add_one
Add_One 10) Add_One(
11
Functions
Chi Zhang
December 5, 2024
A function can be assigned to another. The same functionality exists in R.
def add_one(x):
return x+1
add_one(10)
# now assign this function to another, Add_One
Add_One = add_one
Add_One(10)
11
A function can be the argument of another function
These are functions that are without a name, and has a lambda
keyword. Typically they do not have a name, but you can also assign a name so that it functions like a normal function.
#def greet(name):
# return 'Welcome, ' + name
greet = lambda name: 'Welcome, ' + name
print(greet('Puff'))
print(greet('Ponpon'))
Welcome, Puff
Welcome, Ponpon
Multiple arguments
Execute
Lambda expressions are useful as a function factory,
Syntax: map(<function>, <iterable>)
The iterable does not have to be a list: it can also be a dictionary
#List of names in various cases
names = ["alice", "bob", "CHARLIE", "dEborah"]
# Function to capitalize each name
def capitalize(name):
return name.capitalize()
# Using map() to apply the capitalization to each name
capitalized = map(capitalize, names)
# Converting map object to a list
capitalized = list(capitalized)
print(capitalized)
['Alice', 'Bob', 'Charlie', 'Deborah']
Combined with lambdas
[2, 4, 6]
Filters on a list
The difference between *args
and **kwargs
is that the former receives a tuple, the later receives a dictionary.
def total(numbers):
result = 0
# iterate over the list
for i in numbers:
result += i
return result
nums = [1,2,3,4]
print(total(nums))
10
*args
*args
allows any number of arguments without creating a list before calling. It receives arguments as a tuple (an iterable)
def total(*args): # can also be *number
result = 0
for arg in args: # no *, since it's unpacked
result += arg
return result
print(total(1,2,3)) # no need to create a list, here we have 3 arguments instead of a list
print(total(201,23))
6
224
Recall unpacking in tuples, use *
operator. It unpacks a tuple as a list
three_args = (76, 81, 96)
arg1, arg2, arg3 = three_args
print(arg1)
arg1, *args = three_args # this is where args is
print(args)
76
[81, 96]
The args does not have to be args
, it can take any name as long as the operator is there.
def display(*words):
for item in words: # here no *, since it is unpacked!
print(item)
display('word1')
display('word1', 'word3', 'word4')
display('word1', 3, 24.1) # doesn't have to be a string
word1
word1
word3
word4
word1
3
24.1
When combining with regular arguments, the regular ones must come before *args
def<func> (<argument>, <*args>)
**kwargs
: keyword argumentsThis one receives argument in the form of a dictionary that have key:value pairs. The **
operator unpacks dictionaries into arguments.
def<func> (<argument>, <*args>, <**kwargs>)