Lambda Functio
Lambda Functio
com 30-Jul-2024 Pg 1 of 34
homepage.cs.uiowa.edu/~sriram/16/spring13/notes/March15-2013.pdf
www.cs.cornell.edu/courses/cs3110/2010su/Lectures/AdamByrtekFPinPython.pdf
Benjamin Baka Python Data Structures and Algorithms Copyright © 2017 Packt Publishing pg-21
Benjamin Baka Python Data Structures and Algorithms Copyright © 2017 Packt Publishing pg-22
efaidnbmnnnibpcajpcglclefindmkaj/https://cs.brown.edu/courses/cs004/lectures/lec09.pdf
www.cse.iitd.ac.in/~pkalra/col100/slides/16-HOF.pdf
courses.cs.washington.edu/courses/cse143/12sp/explore/python3.pdf
Simply put, a lambda function is just like any normal python function, except
that it has no name when defining it, and it is contained in one line of code.
A lambda function evaluates an expression for a given argument. You give the
function a value (argument) and then provide the operation (expression). The
keyword lambda must come first. A full colon (:) separates the argument and
the expression.
In the example code below, x is the argument and x+x is the expression.
def a_name(x):
return x+x
#Lambda function
lambda x: x+x
1. Scalar values
This is when you execute a lambda function on a single value.
(lambda x: x*2)(12)
###Results
24
In the code above, the function was created and then immediately executed. This
is an example of an immediately invoked function expression.
2. Lists
filter(). This is a Python inbuilt library that returns only those values that fit
certain criteria. The syntax is filter(function, iterable). The iterable
can be any sequence such as a list, set, or series object (more below).
The example below filters a list for even numbers. Note that the filter function
returns a ‘Filter object’ and you need to encapsulate it with a list to return the
values.
list_1 = [1,2,3,4,5,6,7,8,9]
filter(lambda x: x%2==0, list_1)
### Results
<filter at 0xf378982348>
list(filter(lambda x: x%2==0, list_1))
###Results
[2, 4, 6, 8]
map(). This is another inbuilt python library with the syntax map(function,
iterable).
This returns a modified list where every value in the original list has been
changed based on a function. The example below cubes every number in the list.
list_1 = [1,2,3,4,5,6,7,8,9]
cubed = map(lambda x: pow(x,3), list_1)
list(cubed)
###Results
[1, 8, 27, 64, 125, 216, 343, 512, 729]
Lambdas are important for map(), filter() and reduce() because the arguments
that we pass to them are often short functions needing to be used only once in
our programs, so there’s no use in saving them.
Functional Programming
Using functions as first class objects means to use them in the same manner
that you use data. So, You can pass them as parameters like passing a function
to another function as an argument.
For example, in the following example you can pass the int function as a
parameter to map function.
You can assign them to variables and return them. For example, in the following
code, you can assign the function hello_world, and then the variable will be
executed as a function.
Python functional purity:
There are various built-in functions in Python that can help to avoid procedural
code in functions. So something like this
def naive_sum(list):
s = 0
for l in list:
s += l
return s
can be replaced with the following construct:
sum(list)
Similarly, built-in functions such as map, reduce, and the itertools module in
Python can be utilized to avoid side-effects in your code.
The above construct stems from the traditional thinking of visualizing the whole
program as a series of steps where you define how things need to be done.
lambda function map filter reduce by src7cse @gmail.com 30-Jul-2024 Pg 26 of 34
lambda function map filter reduce by src7cse @gmail.com 30-Jul-2024 Pg 27 of 34
Making this more functional will need a change in the thinking pattern. You can
replace the above for loop in Python in the following manner.
map(func, l)
This is read as “map the function to the list,” which conforms to our idea of
defining the question “what.”
If you take this idea and apply it to the sequential execution of functions, you get
the following construct.
def func1():
pass
def func2():
pass
def func3():
pass
Please note that this does not actually run the functions but returns a lazy map
object. You need to pass this object to a list or any other eager function to have
the code executed.
Python Recursion:
What is Recursion
Recursion is a method of breaking a problem into subproblems which are
essentially of the same type as the original problem. You solve the base
problems and then combine the results. Usually this involves the function calling
itself.
An example for recursion may be something like:
eat the dumplings: 1. check how many dumplings on the plate 2. if no dumplings
left stop eating 3. else eat one dumpling 4. "eat the dumplings"
How to implement recursion in your code
Python functions support recursion and hence you can utilize the dynamic
programming constructs in the code to optimize them. Recursion basically needs
lambda function map filter reduce by src7cse @gmail.com 30-Jul-2024 Pg 27 of 34
lambda function map filter reduce by src7cse @gmail.com 30-Jul-2024 Pg 28 of 34
to fulfill two conditions. There should be a condition where the recursion should
end, and it should call itself for all other conditions. The end condition should be
limiting; i.e, the functions should call smaller versions of themselves.
Example: The following code generates Fibonacci numbers through recursion.
def fib(n):
if n == 0: return 0
elif n == 1: return 1
else: return fib(n-1)+fib(n-2)
A small example showing how to convert procedural code into functional code:
Let us go through a small example where you try to refactor procedural code into
functional. In the below example, you have a starting number which gets
squared, the result is incremented by 1 and the result of that is raised to the
power of 3, the code then takes the decrement. Note that the code works in
steps.
# procedural code
starting_number = 96
The same procedural code can be written functionally. Note that unlike the code
above instead of giving explicit instructions on how to do it, you are giving
instructions on what to do. The functions below operate at a higher plane of
abstraction.
https://www.hackerearth.com/practice/python/functional-programming/functional-
programming-1/tutorial/