0% found this document useful (0 votes)
25 views

Python Lecture 29,30

The document discusses higher order functions and lambda expressions in Python. It provides the objectives and outcomes of a course on Python programming. It also lists topics like functions as first-class objects, lambda expressions and their usage along with examples.

Uploaded by

prakuld04
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Python Lecture 29,30

The document discusses higher order functions and lambda expressions in Python. It provides the objectives and outcomes of a course on Python programming. It also lists topics like functions as first-class objects, lambda expressions and their usage along with examples.

Uploaded by

prakuld04
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

APEX INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Programming in Python (22CSH-287)


Faculty: Mr. Siddharth Kumar (E12853)

Lecture – 29 & 30
DISCOVER . LEARN . EMPOWER
Higher Order Functions 1
COURSE OBJECTIVES

The course aims to:

1) To be able to understand programming skills in Python.


2) To be able to comprehend various operators of Python Programming Language.
3) To demonstrate about Python data structures like Lists, Tuples, Sets and Dictionaries
4) To understand about Functions, Modules and Regular Expressions in Python
Programming.
5) To develop the ability to write applications in Python.

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.

Express proficiency in the handling of conditional statements, loops, strings and


CO2
functions.

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

Unit-2 Contact Hours: 12 Hours

Parts of a Function, Execution of a Function, Keyword and Default Arguments,


Function Scope Rules.

Length of the string and perform concatenation and Repeat operations, Indexing
Strings and Slicing of Strings.

Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,


Python Data Sets, Dictionaries.
Structure
Treat functions as first-class Objects, Lambda Expressions.
Higher Order
Functions

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

Lambda Expressions in Python

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):

# storing the function in a variable

greeting = func("""Hi, I am created by a function

passed as an argument.""")

print (greeting)

greet(shout)

greet(whisper)

Output

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.

hi, i am created by a function passed as an argument. 9


 3. Functions can return another function: Because functions are objects we can return a function from
another function. In the below example, the create_adder function returns adder function.
# Python program to illustrate functions
# Functions can return another function
def create_adder(x):
def adder :
return x+y

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.

format_numeric = lambda num: f"{num:e}" if isinstance(num, int) else f"{num:,.2f}"


print("Int formatting:", format_numeric(1000000))
print("float formatting:", format_numeric(999999.789541235))

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.

With lambda function Without lambda function

Supports single-line sometimes statements that return


Supports any number of lines inside a function block
some value.

Good for performing short operations/data


Good for any cases that require multiple lines of code.
manipulations.

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

You might also like