Python Unit -2
Python Unit -2
Lecture – 16 & 17
DISCOVER . LEARN . EMPOWER
Function 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.
Python Data Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,
Structure Sets, Dictionaries.
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
Parts of a Function
Execution of a Function
Scope Rules
6
What is Function in Python?
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing the same code again and again
for different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
8
Calling a Python Function
After creating a function in Python we can call it by using the name of the function followed by parenthesis
containing parameters of that particular function.
# A simple Python function
def fun():
print("Welcome to GFG")
Output:
Welcome to GFG
9
Python Function with Parameters: If you have experience in C/C++ or Java then you must be thinking
about the return type of the function and data type of arguments. That is possible in Python as well
(specifically for Python 3.5 and above). Defining and calling a function with parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
The following example uses arguments and parameters that you will learn later in this article so you can come
back to it again if not understood.
# Driver code
def add(num1: int, num2: int) -> int:
num1, num2 = 5, 15
"""Add two numbers"""
ans = add(num1, num2)
num3 = num1 + num2 print(f"The addition of {num1} and {num2} results {ans}.")
return num3 10
Python Function Arguments: Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the number passed as an
argument to the function is even or odd.
# A simple Python function to check whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
• Default argument
• Positional arguments
12
Execution of a Function in Python
Default Arguments: A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default arguments.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only argument)
myFun(10)
Output: x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a default value. But once we
have a default argument, all the arguments to its right must also have default values.
13
Keyword Arguments: The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks’)
Output:
Geeks Practice
Geeks Practice
14
Positional Arguments: We used the Position argument during the function call so that the first argument (or
value) is assigned to name and the second argument (or value) is assigned to age. By changing the position, or
if you forget the order of the positions, the values can be used in the wrong places, as shown in the Case-2
example below, where 27 is assigned to the name and Suraj is assigned to the age.
15
Summary
Introduction to Functions: Functions in Python are blocks of reusable code designed to perform a specific
task. They enhance code modularity, readability, and reusability by encapsulating functionality within named
entities.
Parts of a Function:
Function Name: The unique identifier for the function.
Parameters: Input values passed to the function.
Return Type: The type of value the function returns.
Body: The block of code defining the function's actions.
Return Statement: Specifies the value to be returned (optional).
Function Declaration: Functions are declared using the def keyword followed by the function name and
parameters.
The colon : indicates the beginning of the function body. 16
Assessment Questions
Q Define the essential components of a Python function.
Q What is the purpose of each of the following: function name, parameters, return type, function body, and
return statement?
Q Explain the syntax for declaring a function in Python using the def keyword.
Q Why is the colon : used in the function declaration?
Q Differentiate between parameters and arguments in the context of a function.
Q Provide an example of a function with both positional and keyword arguments.
Q What is the role of the return statement in a function?
Q Can a function have multiple return statements?
Q Define the concept of local scope in the context of a function.
Q How does variable scope impact the accessibility of variables in different parts of a program?
17
Assessment Questions
Q How is a function called or invoked in Python?
Q Provide an example of calling a function with arguments.
Q Explain the two ways arguments are matched to parameters during a function call.
Q What is the significance of positional and keyword arguments?
Q How is the return value of a function used in Python?
Q What happens if a function does not have a return statement?
Q Discuss the scope and lifetime of variables within a function.
Q Can a variable defined inside a function be accessed outside the function?
Q What is a docstring, and why is it used in Python functions?
Q Provide an example of a well-documented function using a docstring.
18
THANK YOU
For queries
Email: [email protected]
19
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Lecture – 18 & 19
DISCOVER . LEARN . EMPOWER
Function 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.
Python Data Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,
Structure Sets, Dictionaries.
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
Parts of a Function
Execution of a Function
Scope Rules
6
What Keyword in Python?
Every language contains words and a set of rules that would make a sentence meaningful. Similarly, in Python
programming language, there are a set of predefined words, called Keywords which along with Identifiers will
form meaningful sentences when used together. Python keywords cannot be used as the names of variables,
functions, and classes.
Python Keywords are some predefined and reserved words in Python that have special meanings. Keywords
are used to define the syntax of the coding. The keyword cannot be used as an identifier, function, or variable
name. All the keywords in Python are written in lowercase except True and False. There are 35 keywords in
Python 3.11.
In Python, there is an inbuilt keyword module that provides an iskeyword() function that can be used to check
whether a given string is a valid keyword or not. Furthermore, we can check the name of the keywords in
Python by using the kwlist attribute of the keyword module. Rules for Keywords in Python
• Python keywords cannot be used as identifiers.
• All the keywords in Python should be in lowercase except True and False.
7
List of Python Keywords
Keywords Description
and This is a logical operator which returns true if both the operands are true else returns false.
or This is also a logical operator which returns true if anyone operand is true else returns false.
not This is again a logical operator it returns True if the operand is false else returns false.
if This is used to make a conditional statement.
Elif is a condition statement used with an if statement. The elif statement is executed if the
elif
previous conditions were not true.
Else is used with if and elif conditional statements. The else block is executed if the given
else
condition is not true.
for This is used to create a loop.
while This keyword is used to create a while loop.
break This is used to terminate the loop.
as This is used to create an alternative.
def It helps us to define functions.
lambda It is used to define the anonymous function. 8
List of Python Keywords
Keywords Description
pass This is a null statement which means it will do nothing.
return It will return a value and exit the function.
True This is a boolean value.
False This is also a boolean value.
try It makes a try-except statement.
with The with keyword is used to simplify exception handling.
assert This function is used for debugging purposes. Usually used to check the correctness of code
class It helps us to define a class.
continue It continues to the next iteration of a loop
del It deletes a reference to an object.
except Used with exceptions, what to do when an exception occurs
Finally is used with exceptions, a block of code that will be executed no matter if there is an
finally
exception or not.
from It is used to import specific parts of any module. 9
List of Python Keywords
Keywords Description
from It is used to import specific parts of any module.
global This declares a global variable.
import This is used to import a module.
in It’s used to check whether a value is present in a list, range, tuple, etc.
is This is used to check if the two variables are equal or not.
This is a special constant used to denote a null value or avoid. It’s important to remember, 0, any
none
empty container(e.g empty list) do not compute to None
nonlocal It’s declared a non-local variable.
raise This raises an exception.
yield It ends a function and returns a generator.
async It is used to create asynchronous coroutine.
await It releases the flow of control back to the event loop.
The following code allows you to view the complete list of Python’s keywords.
import keyword
10
print(keyword.kwlist)
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’
are three different identifiers in python. It is a good programming practice to give meaningful names to
identifiers to make the code understandable.
We can also use the Python string isidentifier() method to check whether a string is a valid identifier or not.
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
12
Default Arguments in Python: A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument. The following example illustrates Default arguments.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
Output:
inner pi variable
15
outer pi variable
The above program gives different outputs because the same variable name pi resides in different namespaces,
one inside the function print_pi and the other in the upper level. When print_pi() gets executed, ‘inner pi
variable‘ is printed as that is pi value inside the function namespace. The value ‘outer pi variable‘ is printed
when pi is referenced in the outer namespace. From the above example, we can guess that there definitely is a
rule which is followed, in order in deciding from which namespace a variable has to be picked.
In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope
resolution. The scopes are listed below in terms of hierarchy(highest to lowest/narrowest to broadest):
• Local(L): Defined inside function/class
• Enclosed(E): Defined inside enclosing functions(Nested function concept)
• Global(G): Defined at the uppermost level
• Built-in(B): Reserved names in Python builtin modules
16
Local Scope in Python: Local scope refers to variables defined in the current function. Always, a function
will first look up a variable name in its local scope. Only if it does not find it there, the outer scopes are
checked.
# Local Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()
Output:
inner pi variable
On running the above program, the execution of the inner function prints the value of its local(highest priority
in LEGB rule) variable pi because it is defined and available in the local scope.
17
Local and Global Scopes in Python: If a variable is not defined in the local scope, then, it is checked for in
the higher scope, in this case, the global scope.
# Global Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()
print(pi)
Output: inner pi variable
global pi variable
Therefore, as expected the program prints out the value in the local scope on the execution of inner(). It is
because it is defined inside the function and that is the first place where the variable is looked up. The pi value
18
in global scope is printed on the execution of print(pi) on line 9.
Local, Enclosed, and Global Scopes in Python: For the enclosed scope, we need to define an outer function
enclosing the inner function, comment out the local pi variable of the inner function and refer to pi using the
nonlocal keyword.
# Enclosed Scope
pi = 'global pi variable'
def outer():
pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
nonlocal pi
print(pi)
inner()
outer()
19
print(pi)
Output:
outer pi variable
global pi variable
When outer() is executed, inner() and consequently the print functions are executed, which print the value the
enclosed pi variable.
The statement in line 10 looks for variable in local scope of inner, but does not find it there. Since pi is
referred with the nonlocal keyword, it means that pi needs to be accessed from the outer function(i.e the outer
scope).
To summarize, the pi variable is not found in local scope, so the higher scopes are looked up. It is found in
both enclosed and global scopes. But as per the LEGB hierarchy, the enclosed scope variable is considered
even though we have one defined in the global scope. 20
Local, Enclosed, Global, and Built-in Scopes: The final check can be done by importing pi from math
module and commenting on the global, enclosed, and local pi variables as shown below:
# Built-in Scope
from math import pi
# pi = 'global pi variable'
def outer():
# pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
print(pi)
inner()
outer()
Output:
3.141592653589793 21
Summary
Execution of a Function: Function Call: A function is executed by invoking its name followed by parentheses
containing the arguments.
Argument Matching: Arguments are matched to parameters based on their order (positional) or specified names
(keyword).
Return Value: The return statement signals the end of a function's execution and specifies the value to be
returned.
Keyword and Default Arguments: Keyword Arguments: In function calls, arguments can be passed by
explicitly specifying the parameter names.
Default Arguments: Functions can have default parameter values, allowing the omission of arguments during a
call.
Scope Rules: Local Scope: Variables defined within a function have local scope, accessible only within that
function.
Global Scope: Variables defined outside functions have global scope, accessible throughout the entire program.
22
Assessment Questions
Q Explain the process of calling a function in Python and how it contributes to the execution flow.
Q What is the role of the return statement, and how is it used in a function?
Q Differentiate between positional and keyword arguments in the context of a function call.
Q How are arguments matched to parameters during a function call?
Q Describe how the return value of a function can be utilized in the calling code.
Q Can a function have multiple return statements? Explain.
Q Provide an example of a function call using keyword arguments.
Q In what scenarios are keyword arguments particularly useful?
Q How does using default arguments enhance the flexibility of a function?
Q What are keyword-only arguments, and when might you choose to use them?
Q Can a function have a mix of positional, keyword, and keyword-only arguments?
23
Assessment Questions
Q Define local and global scope in the context of variable visibility.
Q What happens if a variable with the same name exists in both local and global scopes?
Q Explain the lifetime of variables in Python, particularly within a function.
Q When does the existence of local variables cease?
Q Define variable shadowing and provide an example.
Q How does variable shadowing impact variable access in different scopes?
Q What is the purpose of the nonlocal keyword in Python?
Q Provide a scenario where using nonlocal would be necessary.
24
THANK YOU
For queries
Email: [email protected]
25
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
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.
Python Data Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,
Structure Sets, Dictionaries.
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
Length of the String and Perform Concatenation of Strings
6
What is Strings in Python?
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
The computer does not understand the characters; internally, it stores manipulated character as the
combination of the 0's and 1's. Each character is encoded in the ASCII or Unicode character. So we can say
that Python strings are also called the collection of Unicode characters. In Python, strings can be created by
enclosing the character or the sequence of characters in the quotes. Python allows us to use single quotes,
double quotes, or triple quotes to create the string.
Consider the following example in Python to create a string.
Syntax:
str = "Hi Python !"
Here, if we check the type of the variable str using a Python script
print(type(str)), then it will print a string (str).
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the
character data-type; instead, a single character written as 'p' is treated as the string of length 1. 7
Creating String in Python: We can create a string by enclosing the characters in single-quotes or double-
quotes. Python also provides triple-quotes to represent the string, but it is generally used for multiline string or
docstrings.
#Using single quotes
str1 = 'Hello Python'
print(str1)
#Using double quotes
str2 = "Hello Python"
print(str2)
#Using triple quotes
str3 = '''''Triple quotes are generally used for
represent the multiline or
docstring'''
8
print(str3)
Repeat Operations for String in Python: The repetition operator is denoted by a '*' symbol and is useful for
repeating strings to a certain length.
Example:
str = 'Python program'
print(str*3)
The above lines of code will display the following outputs:
Python programPython programPython program
Similarly, it is also possible to repeat any part of the string by slicing:
Example:
str = 'Python program'
print(str[7:9]*3) #Repeats the seventh and eighth character three times
prprpr
9
Indexing and Slicing of Strings in Python
Like other languages, the indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.
O 10
IndexError: string index out of range
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we
can use the : (colon) operator in Python to access the substring from the given string. Consider the following
example.
Here, we must notice that the upper range given in the slice operator is always
exclusive i.e., if str = 'HELLO' is given, then str[1:3] will always include
str[1] = 'E', str[2] = 'L' and nothing else. Consider the following example:
# Given String
str = "JAVATPOINT"
# Starts 2nd index to 3rd index
# Start Oth index to end
print(str[2:4])
print(str[0:]) # Starts 0th to 2nd index
print(str[:3])
# Starts 1th index to 4th index
#Starts 4th to 6th index
print(str[1:5]) print(str[4:7])
11
String Operators:
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings of a particular string.
[:] It is known as range slice operator. It is used to access the characters from the specified range.
It is known as membership operator. It returns if a particular sub-string is present in the specified
in
string.
It is also a membership operator and does the exact reverse of in. It returns true if a particular
not in
substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to print the
r/R actual meaning of escape characters such as "C://python". To define any string as a raw string, the
character r or R is followed by the string.
It is used to perform string formatting. It makes use of the format specifiers used in C programming
%
like %d or %f to map their values in python. We will discuss how formatting is done in python.12
Example: Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
13
Python String Formatting
Escape Sequence: Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given
statement can be written in single quotes or double quotes but it will raise the SyntaxError as it contains both
single and double-quotes.
Example: Consider the following example to understand the real use of Python operators.
str = "They said, "Hello what's going on?""
print(str)
Output:
SyntaxError: invalid syntax
We can use the triple quotes to accomplish this problem but Python provides the escape sequence. The
backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special character and it
interpreted differently. The single quotes inside the string must be escaped. We can apply the same as in the
14
double quotes.
Example
# using triple quotes
print('''''They said, "What's there?"''')
1. \newline It ignores the new line. print("Python1 \Python2 \Python3") Output: Python1 Python2 Python3
Concatenation of Strings: String concatenation involves combining two or more strings into a single string. The
+ operator is commonly used for concatenation in Python.
Repeat Operations for String: Strings can be repeated by using the * operator followed by the desired
repetition count. This operation simplifies the process of creating repeated sequences of characters.
Indexing and Slicing of Strings: Strings are sequences of characters, and each character has an index. Indexing
allows accessing individual characters in a string using their position. Slicing involves extracting a substring or a
portion of the string by specifying a range of indices.
Indexing in Python: Python uses zero-based indexing, where the first character has an index of 0. Negative
indexing allows counting from the end of the string, starting with -1.
23
Summary
Slicing Techniques: Slicing is performed using the syntax string[start:stop], where the resulting substring
includes characters from start to stop-1. Omitting start or stop uses the beginning or end of the string,
respectively. Slicing with a step (string[start:stop:step]) extracts characters with a specified interval.
Immutability of Strings: Strings in Python are immutable, meaning their values cannot be changed once
created. String operations such as concatenation and slicing create new strings rather than modifying existing
ones.
String Methods: Python provides various built-in string methods for performing common operations, including
lower(), upper(), replace(), and find().
Formatting Strings: String formatting allows creating dynamic strings by inserting variable values into
placeholders using techniques like f-strings, format(), or % formatting.
24
Assessment Questions
Q Explain the concept of string concatenation.
Q Provide an example of concatenating two strings using the + operator.
Q How can string concatenation be performed when using variables?
Q Illustrate with an example involving string variables.
Q How can a string be repeated in Python?
Q Demonstrate the use of the * operator for string repetition.
Q Is it possible to dynamically change the repetition count during runtime?
Q Provide an example to support your answer.
Q Explain the concept of indexing in Python strings.
Q How are characters accessed using positive and negative indices?
Q What is the purpose of string slicing in Python?
25
Assessment Questions
Q Provide examples of using string slicing to extract substrings.
Q How does slicing with steps (string[start:stop:step]) work?
Q Demonstrate the use of steps in slicing.
Q What does it mean for strings to be immutable in Python?
Q Discuss the implications of string immutability in terms of operations.
26
THANK YOU
For queries
Email: [email protected]
27
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
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.
Python Data Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,
Structure Sets, Dictionaries.
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
Tuples in Python
Mutable Sequences
6
What is Tuples in Python?
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list
in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is
immutable, unlike the Python list which is mutable.
Creating Python Tuples: There are various ways by which you can create a tuple in Python. They are as
follows:
• Using round brackets
• With one item
• Tuple Constructor
Create Tuples using Round Brackets (): To create a tuple we will use () operators.
var = (“Tuples", “in", “Python")
print(var)
Output:
('Tuples', ‘in', ‘Python') 7
Create a Tuple With One Item: Python 3.11 provides us with another way to create a Tuple.
values : tuple[int | str, ...] = (1,2,4,"Geek")
print(values)
Output: (1, 2, 4, 'Geek')
Here, in the above snippet we are considering a variable called values which holds a tuple that consists of
either int or str, the ‘…’ means that the tuple will hold more than one int or str.
Note: In case your generating a tuple with a single element, make sure to add a comma after the element. Let
us see an example of the same.
mytuple = ("Geeks",)
print(type(mytuple))
#NOT a tuple
mytuple = ("Geeks")
print(type(mytuple))
# adding an element
mytuple[1] = 100
print(mytuple) 10
Output:
Python tuples are ordered and we can access their elements using their index values. They are also immutable,
i.e., we cannot add, remove and change the elements once declared in the tuple, so when we tried to add an
element at index 1, it generated the error.
2
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 11, in
tuple1[1] = 100
TypeError: 'tuple' object does not support item assignment
11
Different Operations Related to Tuples: Below are the different operations related to tuples in Python:
• Concatenation:
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
# Concatenating above two
print(tuple1 + tuple2)
Output: (0, 1, 2, 3, 'python', 'geek')
• Nesting:
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
print(tuple3)
Output :
12
((0, 1, 2, 3), ('python', 'geek'))
• Repetition: Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
Output: ('python', 'python', 'python’)
Note: Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.
(3, 2, 1, 0)
(2, 3)
13
• Deleting: In this example, we are deleting a tuple using ‘del’ keyword. The output will be in the form of error because
after deleting the tuple, it will give a NameError.
Note: Remove individual tuple elements is not possible, but we can delete the whole Tuple using Del
keyword.
• Multiple Data Types with tuples: Tuples in Python are heterogeneous in nature. This means tuples support
elements with multiple datatypes.
# tuple with different datatypes
tuple_obj = ("immutable",True,23)
print(tuple_obj)
Output : ('immutable', True, 23)
15
• Conversion of lists to tuples: We can convert a list in Python to a tuple by using the tuple() constructor and
passing the list as its parameters.
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
# string 'python'
print(tuple('python’))
Output:
Tuples take a single parameter which may be a list, string, set, or even a dictionary(only keys are taken as elements), and
converts them to a tuple.
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
16
• Tuples in a Loop: We can also create a tuple with a single element in it using loops.
# python code for creating tuples in a loop
tup = ('geek',)
# Number of time loop runs
n=5
for i in range(int 5):
tup = (tup,)
print(tup)
Output:
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),) 17
Unpacking Sequences and Lists in Python
Sequence unpacking in python allows you to take objects in a collection and store them in variables for later
use. This is particularly useful when a function or method returns a sequence of objects. In this post, we will
discuss sequence unpacking in python.
A key feature of python is that any sequence can be unpacked into variables by assignment. Consider a list of
values corresponding to the attributes of a specific run on the Nike run application. This list will contain the
date, pace (minutes), time (minutes), distance (miles) and elevation (feet) for a run:
new_run = ['09/01/2020', '10:00', 60, 6, 100]
We can unpack this list with appropriately named variables by assignment:
date, pace, time, distance, elevation = new_run
Let’s now unpack our new sequence:
date, pace, time, distance, elevation, splits = new_run_with_splits
And we can print the mile splits:
18
print("Mile splits: ", splits)
Mutable Sequences in Python
Mutable Sequences are opposite of immutable sequence. They can be changed after the creation. There are
two mutable sequence types in python lists and bytearrays.
Lists: Python lists are very similar to tuples but they don’t have the restrictions of immutability. Lists are
commonly used for storing collections of homogeneous objects, but there is nothing preventing you from
storing heterogeneous collections as well. Lists can be created in many different ways.
ByteArrays: Bytearrays are mutable version of byte objects. They expose most of the casual methods of
mutable sequences as well as most of the methods of the bytes type. Items in a bytearray are integers in the
range[0.256]
Set Types: Python also provides two set types, set and frozenset. The set type is mutable, while frozenset is
immutable. They are unordered collections of immutable objects.
Hashable: An object is an hashale if it has an hashvalue which never changes during it’s lifetime, and can be
compared to other objects. Hashability makes an object usable as a dictionary key and a set member, because
these data structures use the hash value internally.
19
Summary
Tuples in Python:
Definition: Tuples are ordered, immutable collections of elements in Python.
Syntax: Created using parentheses ( ) with comma-separated values.
Immutability: Once defined, elements in a tuple cannot be modified.
Unpacking Sequences and Lists:
Unpacking Tuples: Assigning tuple values to individual variables, facilitating multiple assignments in a single
line. Example: a, b, c = (1, 2, 3)
Unpacking Lists: Lists can also be unpacked similarly, allowing values to be assigned to variables.
Example: x, y, z = [4, 5, 6]
Mutable Sequences:
Mutable sequences, like lists, can be modified after creation.
Immutable sequences, like tuples, cannot be modified once defined. 20
Assessment Questions
Q What is a tuple in Python, and how does it differ from a list?
Q Explain the key characteristics of tuples.
Q Discuss the concept of immutability in tuples.
Q Provide examples demonstrating the immutability of tuples.
Q Explain the concept of unpacking tuples in Python.
Q Provide an example of unpacking a tuple into individual variables.
Q How is unpacking applied to lists in Python?
Q Illustrate with an example of unpacking a list.
Q Contrast the characteristics of lists and tuples in Python.
Q Provide examples of common operations that can be performed on lists.
Q Discuss the mutability of lists and how it differs from tuples.
21
Assessment Questions
Q Provide examples of modifying elements in a list.
Q Define the concept of mutable sequences in Python.
Q List some examples of mutable sequences in addition to lists.
Q Why might one choose to use a mutable sequence over an immutable one?
Q Discuss scenarios where mutable sequences are advantageous.
Q What are the best practices for choosing between tuples and lists in Python?
Q Provide guidelines for when to use each data structure.
Q Discuss the efficiency considerations when using tuples and lists.
Q In what scenarios would the use of tuples be more advantageous?
22
THANK YOU
For queries
Email: [email protected]
23
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
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.
Python Data Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,
Structure Sets, Dictionaries.
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
List Comprehension in Python
Sets in Python
Dictionaries in Python
6
List Comprehension in Python
A Python list comprehension consists of brackets containing the expression, which is executed for each
element along with the for loop to iterate over each element in the Python list.
Example:
numbers = [12, 13, 14,]
doubled = [x *2 for x in numbers]
print(doubled)
Output
[24, 26, 28]
List Comprehensions vs For Loop: There are various ways to iterate through a list. However, the most
common approach is to use the for loop. Let us look at the below example:
# Empty list
List = []
# Traditional approach of iterating
for character in 'Geeks 4 Geeks!':
List.append(character)
# Display list
print(List)
10
Output: ['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
Nested List Comprehensions: Nested List Comprehensions are nothing but a list comprehension within
another list comprehension which is quite similar to nested for loops. Below is the program which implements
nested loop:
matrix = []
for i in range(3):
# Append an empty sublist inside the list
matrix.append([])
for j in range(5):
matrix[i].append(j)
print(matrix)
Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
11
Now by using nested list comprehensions, the same output can be generated in fewer lines of code.
# Nested list comprehension
matrix = [[j for j in range(5)] for i in range(3)]
print(matrix)
Output: [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]
List Comprehensions and Lambda: Lambda Expressions are nothing but shorthand representations of
Python functions. Using list comprehensions with lambda creates an efficient combination. In the given
example, we are inserting numbers from 10 to 50 in the list and printing it.
# using lambda to print table of 10
numbers = []
for i in range(1, 6):
numbers.append(i*10)
print(numbers)
Output: [10, 20, 30, 40, 50] 12
Python List Comprehension using If-else: In the example, we are checking that from 0 to 7 if the number is
even then insert Even Number to the list else insert Odd Number to the list.
lis = ["Even number" if i % 2 == 0
else "Odd number" for i in range(8)]
print(lis)
13
Sets in Python
A Set in Python programming is an unordered collection data type that is iterable, mutable and has no
duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking
whether a specific element is contained in the set. This is based on a data structure known as a hash table.
Since sets are unordered, we cannot access items using indexes as we do in lists.
Example of Python Sets
var = {"Geeks", "for", "Geeks"}
type(var)
Output: set
Time Complexity: O(1)
Auxiliary Space: O(1)
14
Type Casting with Python Set method: The Python set() method is used for type casting.
# typecasting list to set
myset = set(["a", "b", "c"])
print(myset)
# Adding element to the set
myset.add("d")
print(myset)
Output:
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Python set is an unordered datatype, which means we cannot know in which order the elements of the set are
stored.
15
Check unique and Immutable with Python Set: Python sets cannot have a duplicate value and once it is
created we cannot change its value.
# Python program to demonstrate that a set cannot have duplicate values and we cannot change its items a set cannot have
duplicate values
myset = {"Geeks", "for", "Geeks"}
print(myset)
# values of a set cannot be changed
myset[1] = "Hello"
print(myset)
Output: {'Geeks', 'for’}
TypeError: 'set' object does not support item assignment
The first code explains that the set cannot have a duplicate value. Every item in it is a unique value.
The second code generates an error because we cannot assign or change a value once the set is created. We
16
can only add or delete items in the set.
Heterogeneous Element with Python Set: Python sets can store heterogeneous elements in it, i.e., a set can
store a mixture of string, integer, boolean, etc datatypes.
# Python example demonstrate that a set
# can store heterogeneous elements
myset = {"Geeks", "for", 10, 52.7, True}
print(myset)
Output:
{True, 10, 'Geeks', 52.7, 'for’}
Python Frozen Sets: Frozen sets in Python are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied. It can be done with
frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
If no parameters are passed, it returns an empty frozenset. 17
Python program to demonstrate differences between normal and frozen set
# Same as {"a", "b","c"}
normal_set = set(["a", "b","c"])
print("Normal Set")
print(normal_set)
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print("\nFrozen Set")
print(frozen_set)
# Uncommenting below line would cause error as we are trying to add element to a frozen set
frozen_set.add("h")
Output: Normal Set
{'a', 'c', 'b’}
Frozen Set
18
{'e', 'g', 'f'}
Internal working of Set: This is based on a data structure known as a hash table. If Multiple values are
present at the same index position, then the value is appended to that index position, to form a Linked List.
In, Python Sets are implemented using a dictionary with dummy variables, where key beings the members set
with greater optimizations to the time complexity.
Set Implementation:
19
Sets with Numerous operations on a single HashTable:
20
Dictionaries in Python
A dictionary in Python is a data structure that stores the value in value: key pairs.
Example: As you can see from the example, data is stored in key: value pairs in dictionaries, which makes it
easier to find values.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Python Dictionary Syntax
dict_var = {key1 : value1, key2 : value2, …..}
What is a Python Dictionary: Dictionaries in Python is a data structure, used to store values in key: value
format. This makes it different from lists, tuples, and arrays as in a dictionary each key has an associated
value.
Note: As of Python version 3.7, dictionaries are ordered and can not contain duplicate values. 21
How to Create a Dictionary: In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’. The dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its Key: value. Values in a dictionary can be of any data type and can
be duplicated, whereas keys can’t be repeated and must be immutable.
Note: Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
The code demonstrates creating dictionaries with different types of keys. The first dictionary uses integer
keys, and the second dictionary uses a mix of string and integer keys with corresponding values. This
showcases the flexibility of Python dictionaries in handling various data types as keys.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
22
print(Dict)
Different Ways to Create a Python Dictionary: The code demonstrates different ways to create dictionaries
in Python. It first creates an empty dictionary, and then shows how to create dictionaries using the dict()
constructor with key-value pairs specified within curly braces and as a list of tuples.
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Sets in Python: Definition: Sets are unordered collections of unique elements in Python.
Syntax: Created using curly braces {} or the set() constructor.
Unique Elements: Sets automatically enforce uniqueness, making them suitable for distinct elements.
Dictionaries in Python: Definition: Dictionaries are collections of key-value pairs, providing a mapping
between keys and values.
Syntax: Created using curly braces {key: value} or the dict() constructor.
Key-Value Mapping: Enables efficient data retrieval based on keys. 27
Assessment Questions
Q What is list comprehension, and how does it differ from traditional loops?
Q Provide an example of a basic list comprehension.
Q Break down the syntax of a list comprehension and explain each component.
Q How does the optional if condition enhance the functionality of list comprehension?
Q Discuss the advantages of using list comprehension in Python.
Q Provide a real-world use case where list comprehension is beneficial.
Q What are the defining characteristics of sets in Python?
Q How does a set handle duplicate elements?
Q Explain at least three set operations supported in Python.
Q Provide an example demonstrating the use of set operations.
Q In what scenarios are sets particularly useful in Python programming?
28
Assessment Questions
Q Provide an example of a problem that can be efficiently solved using sets.
Q How are dictionaries created in Python, and what is the structure of a dictionary?
Q Provide an example of a dictionary with key-value pairs.
Q Discuss the dynamic nature of dictionaries and how keys and values can be modified.
Q Provide an example illustrating the dynamic nature of dictionaries.
Q List and explain at least three common operations performed on dictionaries.
Q Provide an example showcasing one of these operations.
Q Create a scenario where list comprehension, sets, and dictionaries are used together to solve a problem.
Q Explain the thought process behind choosing each data structure.
29
THANK YOU
For queries
Email: [email protected]
30
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
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.
Python Data Tuples, Unpacking Sequences, Lists, Mutable Sequences, List Comprehension,
Structure Sets, Dictionaries.
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