SlideShare a Scribd company logo
2
Most read
9
Most read
11
Most read
Python Programming
Part V
Megha V
Research Scholar
Kannur University
09-11-2021 meghav@kannuruniv.ac.in 1
Anonymous Functions
• Anonymous function is a function that is defined without a name.
• Anonymous function is defined using the lambda keyword
• Also called lambda functions
syntax
lambda [,arg1 [,arg2,……….argn]]:expression
Eg: # Lambda function definition
square=lambda x : x*x;
# Usage of lambda function
n=int(input(“Enter a number:”))
print(“square of”,n,”is”,square(n)) #
Output
Enter a number:5
Square of 5 is 25
09-11-2021 meghav@kannuruniv.ac.in 2
Main characteristics of lambda function
1. Lambda functions can take any number of arguments but return only one
value in the form of an expression
2. It cannot contain multiple expressions
3. It cannot have comments
4. A lambda function cannot be a direct call to print because lambda requires
an expression
5. Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace
6. Lambda functions are not equivalent to inline functions in C or C++
09-11-2021 meghav@kannuruniv.ac.in 3
• lambda is the keyword, x shows the argument passed, and x*x is the
expression to be evaluated and stored in the variable square
Example with two arguments
# Lambda function definition
sum =lambda x,y : x+y
#usage of lambda function
m=int(input(“Enter first number:”))
n=int(input(“Enter second number:”))
print(“sum of”,m,”and”,n,”is”,sum(m,n))#lambda function call
09-11-2021 meghav@kannuruniv.ac.in 4
Use of lambda function
• We use lambda function when we require a nameless function for a
short period of time.
• Lambda functions are used along with built-in functions like filter(),
map() etc
• The map() function in Python takes input; function and a list.
• The function is called with all the item in the list and a new list is
returned which contains items returned by that function for each
item
09-11-2021 meghav@kannuruniv.ac.in 5
#Lambda function to increment the items in list by 2
oldlist=[2,31,42,11,6,5,23,44]
print(oldlist)
#Usage of lambda function
newlist=list(map(lambda x: x+2,oldlist))
print(“List after incrementation by 2”)
print(newlist)
Output
[2,31,42,11,6,5,23,44]
List after incrementation by 2
[4,33,44,13,8,7,25,46]
lambda function
09-11-2021 meghav@kannuruniv.ac.in 6
• filter() function
• The function filter(function,list) offers a way to filter out all the elements
of a list, for which the function returns True.
• The first argument function returns a Boolean value, i.e., either True or
False.
• This function will be applied to every element of the list lis.
09-11-2021 meghav@kannuruniv.ac.in 7
Example: The function called with all the items in the list and a new list is returned
which contains items for which the function evaluates to True
#Lambda function to filter out only odd numbers from a
list
oldlist=[2,31,42,11,6,5,23,44]
newlist=list(filter(lambda x:(x%2!=0),oldlist))
print(oldlist)
print(newlist)
Output
[2,31,42,11,6,5,23,44]
[31,11,5,23]
09-11-2021 meghav@kannuruniv.ac.in 8
reduce() function
• The function reduce(func,seq) continually applies the fuction func() to the
sequence seq.
• It returns a single value
• If seq=[s1,s2, s3…………….sn], calling reduce(func,seq) work like this:
• At first the two elements of seq will be applied to func, i.e func(s1,s2)
• The list on which reduce() works looks now like this: [func(s1,s2),s3………sn]
• In the next step func will be applied on the previous result and the third
element of the list, i.e. func(func(s1,s2),s3)
• The list looks like this now: [func(func(s1,s2),s3),………,sn]
09-11-2021 meghav@kannuruniv.ac.in 9
• Continue like this until just one element is left and return this element as the
result of reduce()
• Used for performing some computation on list and returning the result.
• The following example illustrates the use of reduce() function, that computes
the product of a list of integers
• Example:
import functools
list=[1,2,3,4]
product=functools.reduce[lambda x,y:x*y,list]
print(list)
print(“Product=” product)
Output
[1,2,3,4]
product=24
09-11-2021 meghav@kannuruniv.ac.in 10
Function with more than one return type
• Instead of writing separate functions for returning individual values, we can return all the values withing
same function
• Example: def cal(a,b)
sum=a+b
diff=a-b
prod=a*b
quotient=a/b
return sum,diff,prod,quotient
a=int(input(“Enter first number:”))
b=int(input(“Enter second number:”))
s,d,p,q=calc(a,b)
print(“Sum=”,s)
print(“Difference=”,d)
print(“Product=”,p)
print(“Quotient=”,q)
Output
Enter first number:10
Enter Second number:5
Sum=15
Difference=5
Product=50
Quotient=5
09-11-2021 meghav@kannuruniv.ac.in 11
Strings
• Python allows several string operators that can be applied on the python
string are as below:
1. Assignment operator: “=.”
2. Concatenate operator: “+.”
3. String repetition operator: “*.”
4. String slicing operator: “[]”
5. String comparison operator: “==” & “!=”
6. Membership operator: “in” & “not in”
7. Escape sequence operator: “.”
8. String formatting operator: “%” & “{}”
09-11-2021 meghav@kannuruniv.ac.in 12
Basic String operations
• Assignment operator: “=.”
string1 = "hello“
• Concatenate operator: “+.”
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
• String repetition operator: “*.”
string1 = "helloworld "
print(string1*2)
09-11-2021 meghav@kannuruniv.ac.in 13
Basic String operations
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
• String slicing operator: “[]”
09-11-2021 meghav@kannuruniv.ac.in 14
Basic String operations
String comparison operator: “==” & “!=”
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4) #False
print(string2==string3) #True
print(string1!=string4) #True
Membership operator: “in” & “not in”
string1 = "helloworld"
print("w" in string1) #True
print("W" in string1) #False
print("t" in string1) #False
print("t" not in string1) #True
print("hello" in string1) #True
print("Hello" in string1) #False
09-11-2021 meghav@kannuruniv.ac.in 15
Basic String operations
• EscapeSequence Operator“.”
• To inserta non-allowedcharacterin thegiveninput string,an escapecharacterisused.
• An escapecharacterisa “” or “backslash”operatorfollowedby a non-allowedcharacter.
string = "Hello world I am from "India""
print(string) #ERROR
string = "Hello world I am from "India""
print(string)
Output
Hello world I am from “India”
09-11-2021 meghav@kannuruniv.ac.in 16
• Escape characters
• An escape character is a character that gets interpreted when placed
in single or double quotes
Escape character Description
a Bell or alert
b Backspace
f Formfeed
n Newline
r Carriage return
s Space
t Tab
v Vertical Tab
09-11-2021 meghav@kannuruniv.ac.in 17
Basic String operations
• String formatting operator: “%” & “{}”
• String formatting operator is used to format a string as per requirement
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Operator Description
%d Signed decimal integer
%u unsigned decimal integer
%c Character
%s String
%f Floating-point real number
09-11-2021 meghav@kannuruniv.ac.in 18
Strings
• Python has a set of built-in methods that you can use on strings.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
09-11-2021 meghav@kannuruniv.ac.in 19
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
09-11-2021 meghav@kannuruniv.ac.in 20
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
09-11-2021 meghav@kannuruniv.ac.in 21
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at
the beginning
09-11-2021 meghav@kannuruniv.ac.in 22
Example
s=‘Learning Python is easy’
print(s.lower())
print(s.title())
print(s.upper())
print(s.swapcase())
print(s.capitalize())
09-11-2021 meghav@kannuruniv.ac.in 23

More Related Content

PPSX
Modules and packages in python
TMARAGATHAM
 
PPT
Time complexity.ppt
YekoyeTigabuYeko
 
PPTX
Datastructures in python
hydpy
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PPTX
Python Functions
Mohammed Sikander
 
PPTX
Space complexity-DAA.pptx
mounikanarra3
 
PPT
Greedy algorithms
Rajendran
 
Modules and packages in python
TMARAGATHAM
 
Time complexity.ppt
YekoyeTigabuYeko
 
Datastructures in python
hydpy
 
Regular expressions in Python
Sujith Kumar
 
Python Functions
Mohammed Sikander
 
Space complexity-DAA.pptx
mounikanarra3
 
Greedy algorithms
Rajendran
 

What's hot (20)

PPTX
Inline function
Tech_MX
 
PPT
FUNCTIONS IN c++ PPT
03062679929
 
PPTX
Functions in Python
Kamal Acharya
 
PPTX
sum of subset problem using Backtracking
Abhishek Singh
 
PPTX
Recursion in c++
Abdul Rehman
 
PPTX
Asymptotic Notation
Protap Mondal
 
PPTX
Functions in Python
Shakti Singh Rathore
 
PPTX
Python Libraries and Modules
RaginiJain21
 
PDF
Strings in python
Prabhakaran V M
 
PPTX
Input-Buffering
Dattatray Gandhmal
 
PDF
Code optimization in compiler design
Kuppusamy P
 
PDF
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
PPTX
LR(1) and SLR(1) parsing
R Islam
 
PPTX
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
PPTX
Python
Aashish Jain
 
PPTX
Intermediate code generator
sanchi29
 
ODP
Python Modules
Nitin Reddy Katkam
 
PPTX
Python Lambda Function
Md Soyaib
 
DOC
CS8391 Data Structures Part B Questions Anna University
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
PPTX
Python Programming Language
Laxman Puri
 
Inline function
Tech_MX
 
FUNCTIONS IN c++ PPT
03062679929
 
Functions in Python
Kamal Acharya
 
sum of subset problem using Backtracking
Abhishek Singh
 
Recursion in c++
Abdul Rehman
 
Asymptotic Notation
Protap Mondal
 
Functions in Python
Shakti Singh Rathore
 
Python Libraries and Modules
RaginiJain21
 
Strings in python
Prabhakaran V M
 
Input-Buffering
Dattatray Gandhmal
 
Code optimization in compiler design
Kuppusamy P
 
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
LR(1) and SLR(1) parsing
R Islam
 
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
Python
Aashish Jain
 
Intermediate code generator
sanchi29
 
Python Modules
Nitin Reddy Katkam
 
Python Lambda Function
Md Soyaib
 
CS8391 Data Structures Part B Questions Anna University
P. Subathra Kishore, KAMARAJ College of Engineering and Technology, Madurai
 
Python Programming Language
Laxman Puri
 
Ad

Similar to Python programming: Anonymous functions, String operations (20)

PPT
python language programming presentation
lbisht2
 
PDF
Python cheatsheat.pdf
HimoZZZ
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
DOCX
Functions.docx
VandanaGoyal21
 
PPTX
Python Revision Tour.pptx class 12 python notes
student164700
 
PPT
asdf adf asdfsdafsdafsdfasdfsdpy llec.ppt
sandhyadevit
 
PPTX
Python Scipy Numpy
Girish Khanzode
 
PDF
Introduction to python
Ahmed Salama
 
PPTX
Python
Sameeksha Verma
 
PPTX
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
PPTX
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
 
PPTX
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
PDF
Python Basics
tusharpanda88
 
PPTX
Python Programming Basics for begginners
Abishek Purushothaman
 
PPTX
PYTHON PPT.pptx python is very useful for day to day life
NaitikSingh33
 
PPTX
Parts of python programming language
Megha V
 
PPTX
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
PDF
Python basic
Saifuddin Kaijar
 
PDF
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
rajkumar2792005
 
PDF
Functions-.pdf
arvdexamsection
 
python language programming presentation
lbisht2
 
Python cheatsheat.pdf
HimoZZZ
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Functions.docx
VandanaGoyal21
 
Python Revision Tour.pptx class 12 python notes
student164700
 
asdf adf asdfsdafsdafsdfasdfsdpy llec.ppt
sandhyadevit
 
Python Scipy Numpy
Girish Khanzode
 
Introduction to python
Ahmed Salama
 
functions.pptxghhhhhhhhhhhhhhhffhhhhhhhdf
pawankamal3
 
ForLoopandUserDefinedFunctions.pptx
AaliyanShaikh
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python Basics
tusharpanda88
 
Python Programming Basics for begginners
Abishek Purushothaman
 
PYTHON PPT.pptx python is very useful for day to day life
NaitikSingh33
 
Parts of python programming language
Megha V
 
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Python basic
Saifuddin Kaijar
 
COMPUTER SCIENCE SUPPORT MATERIAL CLASS 12.pdf
rajkumar2792005
 
Functions-.pdf
arvdexamsection
 
Ad

More from Megha V (20)

PPTX
Soft Computing Techniques_Part 1.pptx
Megha V
 
PPTX
JavaScript- Functions and arrays.pptx
Megha V
 
PPTX
Introduction to JavaScript
Megha V
 
PPTX
Python Exception Handling
Megha V
 
PPTX
Python- Regular expression
Megha V
 
PPTX
File handling in Python
Megha V
 
PPTX
Python programming -Tuple and Set Data type
Megha V
 
PPTX
Python programming –part 7
Megha V
 
PPTX
Python programming Part -6
Megha V
 
PPTX
Python programming- Part IV(Functions)
Megha V
 
PPTX
Python programming –part 3
Megha V
 
PPTX
Python programming
Megha V
 
PPTX
Strassen's matrix multiplication
Megha V
 
PPTX
Solving recurrences
Megha V
 
PPTX
Algorithm Analysis
Megha V
 
PPTX
Algorithm analysis and design
Megha V
 
PPTX
Genetic algorithm
Megha V
 
PPTX
UGC NET Paper 1 ICT Memory and data
Megha V
 
PPTX
Seminar presentation on OpenGL
Megha V
 
PPT
Msc project_CDS Automation
Megha V
 
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Megha V
 
Python Exception Handling
Megha V
 
Python- Regular expression
Megha V
 
File handling in Python
Megha V
 
Python programming -Tuple and Set Data type
Megha V
 
Python programming –part 7
Megha V
 
Python programming Part -6
Megha V
 
Python programming- Part IV(Functions)
Megha V
 
Python programming –part 3
Megha V
 
Python programming
Megha V
 
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Megha V
 
Algorithm Analysis
Megha V
 
Algorithm analysis and design
Megha V
 
Genetic algorithm
Megha V
 
UGC NET Paper 1 ICT Memory and data
Megha V
 
Seminar presentation on OpenGL
Megha V
 
Msc project_CDS Automation
Megha V
 

Recently uploaded (20)

DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
How to Manage Global Discount in Odoo 18 POS
Celine George
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Understanding operators in c language.pptx
auteharshil95
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
How to Manage Global Discount in Odoo 18 POS
Celine George
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 

Python programming: Anonymous functions, String operations

  • 1. Python Programming Part V Megha V Research Scholar Kannur University 09-11-2021 [email protected] 1
  • 2. Anonymous Functions • Anonymous function is a function that is defined without a name. • Anonymous function is defined using the lambda keyword • Also called lambda functions syntax lambda [,arg1 [,arg2,……….argn]]:expression Eg: # Lambda function definition square=lambda x : x*x; # Usage of lambda function n=int(input(“Enter a number:”)) print(“square of”,n,”is”,square(n)) # Output Enter a number:5 Square of 5 is 25 09-11-2021 [email protected] 2
  • 3. Main characteristics of lambda function 1. Lambda functions can take any number of arguments but return only one value in the form of an expression 2. It cannot contain multiple expressions 3. It cannot have comments 4. A lambda function cannot be a direct call to print because lambda requires an expression 5. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace 6. Lambda functions are not equivalent to inline functions in C or C++ 09-11-2021 [email protected] 3
  • 4. • lambda is the keyword, x shows the argument passed, and x*x is the expression to be evaluated and stored in the variable square Example with two arguments # Lambda function definition sum =lambda x,y : x+y #usage of lambda function m=int(input(“Enter first number:”)) n=int(input(“Enter second number:”)) print(“sum of”,m,”and”,n,”is”,sum(m,n))#lambda function call 09-11-2021 [email protected] 4
  • 5. Use of lambda function • We use lambda function when we require a nameless function for a short period of time. • Lambda functions are used along with built-in functions like filter(), map() etc • The map() function in Python takes input; function and a list. • The function is called with all the item in the list and a new list is returned which contains items returned by that function for each item 09-11-2021 [email protected] 5
  • 6. #Lambda function to increment the items in list by 2 oldlist=[2,31,42,11,6,5,23,44] print(oldlist) #Usage of lambda function newlist=list(map(lambda x: x+2,oldlist)) print(“List after incrementation by 2”) print(newlist) Output [2,31,42,11,6,5,23,44] List after incrementation by 2 [4,33,44,13,8,7,25,46] lambda function 09-11-2021 [email protected] 6
  • 7. • filter() function • The function filter(function,list) offers a way to filter out all the elements of a list, for which the function returns True. • The first argument function returns a Boolean value, i.e., either True or False. • This function will be applied to every element of the list lis. 09-11-2021 [email protected] 7
  • 8. Example: The function called with all the items in the list and a new list is returned which contains items for which the function evaluates to True #Lambda function to filter out only odd numbers from a list oldlist=[2,31,42,11,6,5,23,44] newlist=list(filter(lambda x:(x%2!=0),oldlist)) print(oldlist) print(newlist) Output [2,31,42,11,6,5,23,44] [31,11,5,23] 09-11-2021 [email protected] 8
  • 9. reduce() function • The function reduce(func,seq) continually applies the fuction func() to the sequence seq. • It returns a single value • If seq=[s1,s2, s3…………….sn], calling reduce(func,seq) work like this: • At first the two elements of seq will be applied to func, i.e func(s1,s2) • The list on which reduce() works looks now like this: [func(s1,s2),s3………sn] • In the next step func will be applied on the previous result and the third element of the list, i.e. func(func(s1,s2),s3) • The list looks like this now: [func(func(s1,s2),s3),………,sn] 09-11-2021 [email protected] 9
  • 10. • Continue like this until just one element is left and return this element as the result of reduce() • Used for performing some computation on list and returning the result. • The following example illustrates the use of reduce() function, that computes the product of a list of integers • Example: import functools list=[1,2,3,4] product=functools.reduce[lambda x,y:x*y,list] print(list) print(“Product=” product) Output [1,2,3,4] product=24 09-11-2021 [email protected] 10
  • 11. Function with more than one return type • Instead of writing separate functions for returning individual values, we can return all the values withing same function • Example: def cal(a,b) sum=a+b diff=a-b prod=a*b quotient=a/b return sum,diff,prod,quotient a=int(input(“Enter first number:”)) b=int(input(“Enter second number:”)) s,d,p,q=calc(a,b) print(“Sum=”,s) print(“Difference=”,d) print(“Product=”,p) print(“Quotient=”,q) Output Enter first number:10 Enter Second number:5 Sum=15 Difference=5 Product=50 Quotient=5 09-11-2021 [email protected] 11
  • 12. Strings • Python allows several string operators that can be applied on the python string are as below: 1. Assignment operator: “=.” 2. Concatenate operator: “+.” 3. String repetition operator: “*.” 4. String slicing operator: “[]” 5. String comparison operator: “==” & “!=” 6. Membership operator: “in” & “not in” 7. Escape sequence operator: “.” 8. String formatting operator: “%” & “{}” 09-11-2021 [email protected] 12
  • 13. Basic String operations • Assignment operator: “=.” string1 = "hello“ • Concatenate operator: “+.” string1 = "hello" string2 = "world " string_combined = string1+string2 print(string_combined) • String repetition operator: “*.” string1 = "helloworld " print(string1*2) 09-11-2021 [email protected] 13
  • 14. Basic String operations string1 = "helloworld" print(string1[1]) print(string1[-3]) print(string1[1:5]) print(string1[1:-3]) print(string1[2:]) print(string1[:5]) print(string1[:-2]) print(string1[-2:]) print(string1[::-1]) • String slicing operator: “[]” 09-11-2021 [email protected] 14
  • 15. Basic String operations String comparison operator: “==” & “!=” string1 = "hello" string2 = "hello, world" string3 = "hello, world" string4 = "world" print(string1==string4) #False print(string2==string3) #True print(string1!=string4) #True Membership operator: “in” & “not in” string1 = "helloworld" print("w" in string1) #True print("W" in string1) #False print("t" in string1) #False print("t" not in string1) #True print("hello" in string1) #True print("Hello" in string1) #False 09-11-2021 [email protected] 15
  • 16. Basic String operations • EscapeSequence Operator“.” • To inserta non-allowedcharacterin thegiveninput string,an escapecharacterisused. • An escapecharacterisa “” or “backslash”operatorfollowedby a non-allowedcharacter. string = "Hello world I am from "India"" print(string) #ERROR string = "Hello world I am from "India"" print(string) Output Hello world I am from “India” 09-11-2021 [email protected] 16
  • 17. • Escape characters • An escape character is a character that gets interpreted when placed in single or double quotes Escape character Description a Bell or alert b Backspace f Formfeed n Newline r Carriage return s Space t Tab v Vertical Tab 09-11-2021 [email protected] 17
  • 18. Basic String operations • String formatting operator: “%” & “{}” • String formatting operator is used to format a string as per requirement name = "india" age = 19 marks = 20.56 string1 = 'Hey %s' % (name) print(string1) string2 = 'my age is %d' % (age) print(string2) string3= 'Hey %s, my age is %d' % (name, age) print(string3) string3= 'Hey %s, my subject mark is %f' % (name, marks) print(string3) Operator Description %d Signed decimal integer %u unsigned decimal integer %c Character %s String %f Floating-point real number 09-11-2021 [email protected] 18
  • 19. Strings • Python has a set of built-in methods that you can use on strings. Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isascii() Returns True if all characters in the string are ascii characters 09-11-2021 [email protected] 19
  • 20. isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Converts the elements of an iterable into a string ljust() Returns a left justified version of the string lower() Converts a string into lower case 09-11-2021 [email protected] 20
  • 21. lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value rfind() Searches the string for a specified value and returns the last position of where it was found rindex() Searches the string for a specified value and returns the last position of where it was found rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list 09-11-2021 [email protected] 21
  • 22. splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning 09-11-2021 [email protected] 22
  • 23. Example s=‘Learning Python is easy’ print(s.lower()) print(s.title()) print(s.upper()) print(s.swapcase()) print(s.capitalize()) 09-11-2021 [email protected] 23