Advanced Functions Part 2
Mutable Structures¶
There are some exceptions with scope to be aware of, and one example is lists. They are mutable meaning when we pass in a list to a function we are actually passing a reference to it in the memory of our machine. If we change it within a function, we change it everywhere!
If we have a function that doubles the first value in a list each time then prints it, we can see that the number is actually being changed outside the function.
#This is going to actually double the elements outside the function
def double(l):
l[0] = l[0]*2
print(l)
l = [1,2,3]
double(l)
double(l)
double(l)
Copying a List¶
If you want to pass in a copy of a list instead of the actual list, you can either pass it as l[:] or l.copy() and then anything that happens to the list in the function won't change the original list.
#The way to work around this is to give a copy of the list or a slice of the list, for example....
l = [1,2,3]
double(l[:])
double(l.copy())
double(l[:])
double(l.copy())
Nested Functions¶
Functions may be nested within one and if you would like. The following definition will define for us f1 which within its scope defines f2, a function to square something. Then we multiply the argument a by 2, and then apply our defined function before returning it.
#It is also possible to define functions within functions, so for this we have f1, and also f2 defined within it
def f1(a):
def f2(b):
return b**2
a = a*2
a = f2(a)
return a
#So we multiply a by 2, then square it with f2
print(f1(3))
When you nest a function it is not defined outside the function scope. The code below fails for this reason.
#These functions are NOT defined outside of the f1 function however
#So you'll get an error
f2(3)
Lambda Functions¶
Lambda functions are a way to define in short hand a function. They become very useful when we need simple one line functions. The format is:
y = lambda x: f(x)
where y then becomes the function you created. Below is a function which creates y, a function to square any input.
#Finally, lambda is a short hand way to define a function
#Call lambda x: followed by what you want x to be returned as
y = lambda x: x**2
#So we now square 2 with the y function
print(y(2))