Python Lecture 29,30
Python Lecture 29,30
Lecture – 29 & 30
DISCOVER . LEARN . EMPOWER
Higher Order Functions 1
COURSE OBJECTIVES
2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-
Identify and interpret the basics syntax of Python Programming Language and be fluent
CO1
in the use of Python.
Understanding the data structures like Lists, Tuples, Sets and Dictionaries in
CO3
programming paradigms of Python Programming Language.
Ability to create practical and contemporary applications using Functions, Abstract Data
CO4
Types and Modules in Python.
Implementation of Python based applications using file input and output operations in
CO5
Python Programming.
3
Unit-2 Syllabus
Length of the string and perform concatenation and Repeat operations, Indexing
Strings and Slicing of Strings.
4
SUGGESTIVE READINGS
Text Books / Reference Books
TEXT BOOKS
T1: Allen B. Downey, “Think Python: How to Think Like a Computer Scientist” 2nd Edition, Version 2.4.0, O'Reilly Media, Inc.";
2012 Aug 13.
T2: Dierbach, Charles. Introduction to computer science using python: A computational problem-solving focus. Wiley
Publishing, 2012.
T3: Guido van Rossum and Fred L. Drake Jr, -An Introduction to Python - Revised and updated for Python 3.2, Network Theory
Ltd., 2011.
T4: Andreas C. Müller, Sarah Guido, ― "Introduction to Machine Learning with Python",O'Reilly Media, Inc.; 2016.
REFERENCE BOOKS
R1: Timothy A. Budd, ―Exploring Python, Mc-Graw Hill Education (India) Private Ltd. 2015.
R2: Kenneth A. Lambert, ―Fundamentals of Python: First Programs, CENGAGE Learning, 2012.
R3: Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem Solving Focus, Wiley India
Edition, 2013.
R4: Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using
Python 3, Second edition, Pragmatic Programmers, LLC, 2013.
5
Contents to be covered
Treat Functions as First-Class Objects
6
Treat Functions as First-Class Objects in Python
First class objects in a language are handled uniformly throughout. They may be stored in data structures,
passed as arguments, or used in control structures. A programming language is said to support first-class
functions if it treats functions as first-class objects. Python supports the concept of First Class functions.
Properties of first class functions:
• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables, lists, …
Examples illustrating First Class functions in Python
1. Functions are objects: Python functions are first class objects. In the example below, we are assigning
function to a variable. This assignment doesn’t call the function. It takes the function object referenced by
7
shout and creates a second name pointing to it, yell.
# Python program to illustrate functions
# can be treated as objects
def shout(text):
return text.upper()
print (shout('Hello'))
yell = shout
print (yell('Hello'))
Output:
HELLO
HELLO
8
2. Functions can be passed as arguments to other functions: Because functions are objects we can pass
them as arguments to other functions. Functions that can accept other functions as arguments are also called
higher-order functions. In the example below, we have created a function greet which takes a function as an
argument.
# Python program to illustrate functions can be passed as arguments to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
passed as an argument.""")
print (greeting)
greet(shout)
greet(whisper)
Output
return adder
add_15 = create_adder(15)
print (add_15(10))
Output: 25
10
Lambda Expressions in Python
Python Lambda Functions are anonymous functions means that the function is without a name. As we already
know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used
to define an anonymous function in Python.
Python Lambda Function Syntax
Syntax:
lambda arguments : expression
• This function can have any number of arguments but only one expression, which is evaluated and
returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically restricted to a single
expression.
• It has various uses in particular fields of programming, besides other types of expressions in functions.
11
Python Lambda Function Example: In the example, we defined a lambda function(upper) to convert a
string to its upper case using upper().
This code defines a lambda function named upper that takes a string as its argument and converts it to
uppercase using the upper() method. It then applies this lambda function to the string ‘GeeksforGeeks’ and
prints the result.
str1 = 'GeeksforGeeks'
upper = lambda string: string.upper()
print(upper(str1))
Output:
GEEKSFORGEEKS
12
Use of Lambda Function in Python: Let’s see some of the practical uses of the Python lambda function.
Condition Checking Using Python lambda function: Here, the ‘format_numric’ calls the lambda function,
and the num is passed as a parameter to perform operations.
Output:
Int formatting: 1.000000e+06
float formatting: 999,999.79
13
Difference Between Lambda functions and def defined function
The code defines a cube function using both the ‘def' keyword and a lambda function. It calculates the cube
of a given number (5 in this case) using both approaches and prints the results. The output is 125 for both the
‘def' and lambda functions, demonstrating that they achieve the same cube calculation.
Using the lambda function can sometime reduce the We can use comments and function descriptions for
readability of code. easy readability.
14
Summary
Functions as First-Class Objects: Definition: In Python, functions are first-class objects, meaning they can be:
Assigned to variables.
Passed as arguments to other functions.
Returned as values from other functions.
Characteristics of First-Class Functions: Assignability: Functions can be assigned to variables, making them
accessible by the variable name.
Passing as Arguments: Functions can be passed as arguments to other functions.
Return Values: Functions can be returned as values from other functions.
Use Cases for First-Class Functions: Higher-Order Functions: Functions that take other functions as arguments
or return them.
Functional Programming Paradigm: Supports functional programming concepts like map, filter, and reduce.
15
Summary
Lambda Expressions: Definition: Lambda expressions (anonymous functions) allow the creation of small,
unnamed functions on the fly.
Syntax: lambda arguments: expression.
Simplicity: Lambda functions are concise and used for short-term, one-off operations.
Characteristics of Lambda Expressions: Single Expression: Lambda functions consist of a single expression,
eliminating the need for a return statement.
Anonymous Nature: Lambda functions are anonymous and don't require a defined name.
Brief Syntax: Lambda expressions are more compact than regular function declarations.
Use Cases for Lambda Expressions: Map, Filter, and Reduce: Lambda functions are often used in conjunction
with these higher-order functions.
Sorting: Lambda functions can be employed as key functions for sorting. 16
Assessment Questions
Q Explain the characteristics that define functions as first-class objects in Python.
Q Provide an example illustrating the assignability of functions to variables.
Q Describe situations where treating functions as first-class objects is particularly advantageous.
Q Provide an example of a higher-order function that takes another function as an argument.
Q What is the functional programming paradigm, and how does Python support it through first-class functions?
Q Explain the relevance of immutability and higher-order functions in functional programming.
Q Define what a lambda expression is in Python.
Q Provide the basic syntax for a lambda expression.
Q Discuss the characteristics that differentiate lambda expressions from regular function declarations.
Q Explain why lambda functions are considered anonymous.
Q Describe scenarios where using lambda expressions is more appropriate than declaring regular functions.
17
Q Provide examples of employing lambda functions with higher-order functions like map and filter.
THANK YOU
For queries
Email: [email protected]
18