This document discusses functions and methods in Python. It defines functions and methods, and explains the differences between them. It provides examples of defining and calling functions, returning values from functions, and passing arguments to functions. It also covers topics like local and global variables, function decorators, generators, modules, and lambda functions.
Python lambda functions with filter, map & reduce functionARVIND PANDE
Lambda functions allow the creation of small anonymous functions and can be passed as arguments to other functions. The map() function applies a lambda function to each element of a list and returns a new list. The filter() function filters a list based on the return value of a lambda function. The reduce() function iteratively applies a lambda function to consecutive pairs in a list and returns a single value. User-defined functions in Python can perform tasks like converting between temperature scales, finding max/min/average of lists, generating Fibonacci series, reversing strings, summing digits in numbers, and calculating powers using recursion.
The document discusses functions in Python. It describes what functions are, different types of built-in functions like abs(), min(), max() etc. It also discusses commonly used modules like math, random, importing modules and functions within modules. It explains function definition, parameters, scope and lifetime of variables, return statement, default parameters, keyword arguments, variable length arguments and command line arguments.
The document provides information on Python functions including defining, calling, passing arguments to, and scoping of functions. Some key points covered:
- Functions allow for modular and reusable code. User-defined functions in Python are defined using the def keyword.
- Functions can take arguments, have docstrings, and use return statements. Arguments are passed by reference in Python.
- Functions can be called by name and arguments passed positionally or by keyword. Default and variable arguments are also supported.
- Anonymous lambda functions can take arguments and return an expression.
- Variables in a function have local scope while global variables defined outside a function can be accessed anywhere. The global keyword is used to modify global variables from within a function
The document provides information on Python functions including defining, calling, passing arguments to, and scoping of functions. Some key points covered:
- Functions allow for modular and reusable code. User-defined functions in Python are defined using the def keyword.
- Functions can take arguments, have docstrings, and use return statements. Arguments are passed by reference in Python.
- Functions can be called by name and arguments passed positionally or by keyword. Default and variable arguments are also supported.
- Anonymous lambda functions can take arguments and return an expression.
- Variables in a function have local scope while global variables defined outside a function can be accessed anywhere. The global keyword is used to modify global variables from within a function
Python programming - Functions and list and tuplesMalligaarjunanN
- A function is a block of reusable code that takes in parameters, performs an action, and returns a value. Functions provide modularity and code reusability.
- Functions in Python are defined using the def keyword followed by the function name and parameters in parentheses. The code block is indented and can return a value. Parameters can have default values.
- Functions can take positional arguments, keyword arguments, and variable length arguments. Parameters are passed by reference, so changes inside the function also affect the variables outside.
- Anonymous functions called lambdas are small single expression functions defined with the lambda keyword. They do not have a name and cannot contain multiple expressions or statements.
This document discusses functions in Python. It defines what a function is and provides the basic syntax for defining a function using the def keyword. It also covers function parameters, including required, keyword, default, and variable-length arguments. The document explains how to call functions and discusses pass by reference vs pass by value. Additionally, it covers anonymous functions, function scope, and global vs local variables.
Chapter Functions for grade 12 computer ScienceKrithikaTM
1. A function is a block of code that performs a specific task and can be called anywhere in a program. Functions make code reusable, improve modularity, and make programs easier to understand.
2. There are three main types of functions: built-in functions, functions defined in modules, and user-defined functions. Built-in functions are pre-defined and always available, module functions require importing, and user-defined functions are created by programmers.
3. Functions improve code organization and readability by separating code into logical, modular units. Functions can take parameters, return values, and be called from other parts of a program or other functions. This allows for code reuse and modular programming.
This document discusses functions in Python. It begins by defining what a function is and provides examples of built-in functions and functions defined in modules. It then lists some advantages of using functions such as code reusability and readability. The document discusses the different types of functions - built-in functions, functions defined in modules, and user-defined functions. It provides examples of each type. The document also covers topics such as function parameters, return values, variable scope, lambda functions, and using functions from libraries.
This document discusses passing lists and tuples as arguments to functions in Python. It provides examples of passing a list to a function, which allows the function to iterate through the list. It also discusses variable-length arguments using an asterisk, and provides an example of a function that accepts additional unnamed arguments as a tuple. Finally, it discusses anonymous functions in Python using the lambda keyword, and provides an example of defining and calling an anonymous function.
This document discusses functions in Python. It defines a function as a block of code that performs a specific task and can be called when needed. Functions make programs easier to develop, test and reuse code. The document covers creating and calling user-defined functions, variable scope, passing arguments and return values, lambda functions, mutable and immutable objects, and built-in functions for common tasks like math operations and string manipulation.
Functions are blocks of code that perform tasks and are called when needed. User-defined functions in Python are created using the def keyword. Functions make code reusable, increase readability and modularity. Variables inside functions have local scope unless declared as global or nonlocal. Functions can take arguments and return values. Libraries contain many built-in functions for tasks like math operations and string manipulation.
The document discusses functions in Python. It defines a function as a block of code that performs a specific task and only runs when called. Functions can take parameters as input and return values. Some key points covered include:
- User-defined functions can be created in Python in addition to built-in functions.
- Functions make code reusable, readable, and modular. They allow for easier testing and maintenance of code.
- Variables can have local, global, or non-local scope depending on where they are used.
- Functions can take positional/required arguments, keyword arguments, default arguments, and variable length arguments.
- Objects passed to functions can be mutable like lists, causing pass by
The document discusses functions in Python. It defines a function as a block of code that performs a specific task and can be called when needed. Functions make code reusable, readable, and help divide programs into modular pieces. The document covers built-in functions, user-defined functions, passing arguments to functions, scope of variables, mutable and immutable objects, and functions available in Python libraries like math and string functions.
This document discusses functions in Python. It begins by defining what a function is - a block of code that performs a specific task and only runs when called. User-defined functions can be created in Python. The document outlines the advantages of using functions such as code reusability and readability. It provides an example of defining and calling a simple function. It also discusses variable scope in functions, including local, global, and nonlocal variables. Finally, it covers passing different data types like numbers, lists, dictionaries and strings to functions.
This document discusses functions in Python. It begins by defining what a function is - a block of code that performs a specific task and only runs when called. User-defined functions can be created in Python. The document outlines the advantages of using functions such as code reusability and readability. It provides an example of defining and calling a simple function. It discusses variable scope within functions and different types of arguments that can be passed to functions. The document also covers passing different data types like lists, dictionaries and strings to functions. Finally, it discusses using functions from library modules like math and string functions.
A brief introduction to functional programming.
Even if slides present some simple Python code, functional programming patterns applies to other languages too.
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
Ad
More Related Content
Similar to Function in Python.pptx by Faculty at gla university in mathura uttar pradesh (20)
The document discusses functions in Python. It describes what functions are, different types of built-in functions like abs(), min(), max() etc. It also discusses commonly used modules like math, random, importing modules and functions within modules. It explains function definition, parameters, scope and lifetime of variables, return statement, default parameters, keyword arguments, variable length arguments and command line arguments.
The document provides information on Python functions including defining, calling, passing arguments to, and scoping of functions. Some key points covered:
- Functions allow for modular and reusable code. User-defined functions in Python are defined using the def keyword.
- Functions can take arguments, have docstrings, and use return statements. Arguments are passed by reference in Python.
- Functions can be called by name and arguments passed positionally or by keyword. Default and variable arguments are also supported.
- Anonymous lambda functions can take arguments and return an expression.
- Variables in a function have local scope while global variables defined outside a function can be accessed anywhere. The global keyword is used to modify global variables from within a function
The document provides information on Python functions including defining, calling, passing arguments to, and scoping of functions. Some key points covered:
- Functions allow for modular and reusable code. User-defined functions in Python are defined using the def keyword.
- Functions can take arguments, have docstrings, and use return statements. Arguments are passed by reference in Python.
- Functions can be called by name and arguments passed positionally or by keyword. Default and variable arguments are also supported.
- Anonymous lambda functions can take arguments and return an expression.
- Variables in a function have local scope while global variables defined outside a function can be accessed anywhere. The global keyword is used to modify global variables from within a function
Python programming - Functions and list and tuplesMalligaarjunanN
- A function is a block of reusable code that takes in parameters, performs an action, and returns a value. Functions provide modularity and code reusability.
- Functions in Python are defined using the def keyword followed by the function name and parameters in parentheses. The code block is indented and can return a value. Parameters can have default values.
- Functions can take positional arguments, keyword arguments, and variable length arguments. Parameters are passed by reference, so changes inside the function also affect the variables outside.
- Anonymous functions called lambdas are small single expression functions defined with the lambda keyword. They do not have a name and cannot contain multiple expressions or statements.
This document discusses functions in Python. It defines what a function is and provides the basic syntax for defining a function using the def keyword. It also covers function parameters, including required, keyword, default, and variable-length arguments. The document explains how to call functions and discusses pass by reference vs pass by value. Additionally, it covers anonymous functions, function scope, and global vs local variables.
Chapter Functions for grade 12 computer ScienceKrithikaTM
1. A function is a block of code that performs a specific task and can be called anywhere in a program. Functions make code reusable, improve modularity, and make programs easier to understand.
2. There are three main types of functions: built-in functions, functions defined in modules, and user-defined functions. Built-in functions are pre-defined and always available, module functions require importing, and user-defined functions are created by programmers.
3. Functions improve code organization and readability by separating code into logical, modular units. Functions can take parameters, return values, and be called from other parts of a program or other functions. This allows for code reuse and modular programming.
This document discusses functions in Python. It begins by defining what a function is and provides examples of built-in functions and functions defined in modules. It then lists some advantages of using functions such as code reusability and readability. The document discusses the different types of functions - built-in functions, functions defined in modules, and user-defined functions. It provides examples of each type. The document also covers topics such as function parameters, return values, variable scope, lambda functions, and using functions from libraries.
This document discusses passing lists and tuples as arguments to functions in Python. It provides examples of passing a list to a function, which allows the function to iterate through the list. It also discusses variable-length arguments using an asterisk, and provides an example of a function that accepts additional unnamed arguments as a tuple. Finally, it discusses anonymous functions in Python using the lambda keyword, and provides an example of defining and calling an anonymous function.
This document discusses functions in Python. It defines a function as a block of code that performs a specific task and can be called when needed. Functions make programs easier to develop, test and reuse code. The document covers creating and calling user-defined functions, variable scope, passing arguments and return values, lambda functions, mutable and immutable objects, and built-in functions for common tasks like math operations and string manipulation.
Functions are blocks of code that perform tasks and are called when needed. User-defined functions in Python are created using the def keyword. Functions make code reusable, increase readability and modularity. Variables inside functions have local scope unless declared as global or nonlocal. Functions can take arguments and return values. Libraries contain many built-in functions for tasks like math operations and string manipulation.
The document discusses functions in Python. It defines a function as a block of code that performs a specific task and only runs when called. Functions can take parameters as input and return values. Some key points covered include:
- User-defined functions can be created in Python in addition to built-in functions.
- Functions make code reusable, readable, and modular. They allow for easier testing and maintenance of code.
- Variables can have local, global, or non-local scope depending on where they are used.
- Functions can take positional/required arguments, keyword arguments, default arguments, and variable length arguments.
- Objects passed to functions can be mutable like lists, causing pass by
The document discusses functions in Python. It defines a function as a block of code that performs a specific task and can be called when needed. Functions make code reusable, readable, and help divide programs into modular pieces. The document covers built-in functions, user-defined functions, passing arguments to functions, scope of variables, mutable and immutable objects, and functions available in Python libraries like math and string functions.
This document discusses functions in Python. It begins by defining what a function is - a block of code that performs a specific task and only runs when called. User-defined functions can be created in Python. The document outlines the advantages of using functions such as code reusability and readability. It provides an example of defining and calling a simple function. It also discusses variable scope in functions, including local, global, and nonlocal variables. Finally, it covers passing different data types like numbers, lists, dictionaries and strings to functions.
This document discusses functions in Python. It begins by defining what a function is - a block of code that performs a specific task and only runs when called. User-defined functions can be created in Python. The document outlines the advantages of using functions such as code reusability and readability. It provides an example of defining and calling a simple function. It discusses variable scope within functions and different types of arguments that can be passed to functions. The document also covers passing different data types like lists, dictionaries and strings to functions. Finally, it discusses using functions from library modules like math and string functions.
A brief introduction to functional programming.
Even if slides present some simple Python code, functional programming patterns applies to other languages too.
This paper proposes a shoulder inverse kinematics (IK) technique. Shoulder complex is comprised of the sternum, clavicle, ribs, scapula, humerus, and four joints.
Passenger car unit (PCU) of a vehicle type depends on vehicular characteristics, stream characteristics, roadway characteristics, environmental factors, climate conditions and control conditions. Keeping in view various factors affecting PCU, a model was developed taking a volume to capacity ratio and percentage share of particular vehicle type as independent parameters. A microscopic traffic simulation model VISSIM has been used in present study for generating traffic flow data which some time very difficult to obtain from field survey. A comparison study was carried out with the purpose of verifying when the adaptive neuro-fuzzy inference system (ANFIS), artificial neural network (ANN) and multiple linear regression (MLR) models are appropriate for prediction of PCUs of different vehicle types. From the results observed that ANFIS model estimates were closer to the corresponding simulated PCU values compared to MLR and ANN models. It is concluded that the ANFIS model showed greater potential in predicting PCUs from v/c ratio and proportional share for all type of vehicles whereas MLR and ANN models did not perform well.
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYijscai
With the increased use of Artificial Intelligence (AI) in malware analysis there is also an increased need to
understand the decisions models make when identifying malicious artifacts. Explainable AI (XAI) becomes
the answer to interpreting the decision-making process that AI malware analysis models use to determine
malicious benign samples to gain trust that in a production environment, the system is able to catch
malware. With any cyber innovation brings a new set of challenges and literature soon came out about XAI
as a new attack vector. Adversarial XAI (AdvXAI) is a relatively new concept but with AI applications in
many sectors, it is crucial to quickly respond to the attack surface that it creates. This paper seeks to
conceptualize a theoretical framework focused on addressing AdvXAI in malware analysis in an effort to
balance explainability with security. Following this framework, designing a machine with an AI malware
detection and analysis model will ensure that it can effectively analyze malware, explain how it came to its
decision, and be built securely to avoid adversarial attacks and manipulations. The framework focuses on
choosing malware datasets to train the model, choosing the AI model, choosing an XAI technique,
implementing AdvXAI defensive measures, and continually evaluating the model. This framework will
significantly contribute to automated malware detection and XAI efforts allowing for secure systems that
are resilient to adversarial attacks.
The role of the lexical analyzer
Specification of tokens
Finite state machines
From a regular expressions to an NFA
Convert NFA to DFA
Transforming grammars and regular expressions
Transforming automata to grammars
Language for specifying lexical analyzers
π0.5: a Vision-Language-Action Model with Open-World GeneralizationNABLAS株式会社
今回の資料「Transfusion / π0 / π0.5」は、画像・言語・アクションを統合するロボット基盤モデルについて紹介しています。
拡散×自己回帰を融合したTransformerをベースに、π0.5ではオープンワールドでの推論・計画も可能に。
This presentation introduces robot foundation models that integrate vision, language, and action.
Built on a Transformer combining diffusion and autoregression, π0.5 enables reasoning and planning in open-world settings.
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxRishavKumar530754
LiDAR-Based System for Autonomous Cars
Autonomous Driving with LiDAR Tech
LiDAR Integration in Self-Driving Cars
Self-Driving Vehicles Using LiDAR
LiDAR Mapping for Driverless Cars
In tube drawing process, a tube is pulled out through a die and a plug to reduce its diameter and thickness as per the requirement. Dimensional accuracy of cold drawn tubes plays a vital role in the further quality of end products and controlling rejection in manufacturing processes of these end products. Springback phenomenon is the elastic strain recovery after removal of forming loads, causes geometrical inaccuracies in drawn tubes. Further, this leads to difficulty in achieving close dimensional tolerances. In the present work springback of EN 8 D tube material is studied for various cold drawing parameters. The process parameters in this work include die semi-angle, land width and drawing speed. The experimentation is done using Taguchi’s L36 orthogonal array, and then optimization is done in data analysis software Minitab 17. The results of ANOVA shows that 15 degrees die semi-angle,5 mm land width and 6 m/min drawing speed yields least springback. Furthermore, optimization algorithms named Particle Swarm Optimization (PSO), Simulated Annealing (SA) and Genetic Algorithm (GA) are applied which shows that 15 degrees die semi-angle, 10 mm land width and 8 m/min drawing speed results in minimal springback with almost 10.5 % improvement. Finally, the results of experimentation are validated with Finite Element Analysis technique using ANSYS.
its all about Artificial Intelligence(Ai) and Machine Learning and not on advanced level you can study before the exam or can check for some information on Ai for project
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
1. Function in Python
def function_name( parameters ):
‘’’function_docstring’’’
function_suite
return [expression]
2. def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Value inside function: 10
Value outside function: 20
3. Pass by Reference vs Value
def changeme( mylist1 ):
"This changes a passed list into this function"
print ("before change: ", mylist1)
mylist1[2]=50
print ("after change: ", mylist1)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
4. • Here, we are maintaining reference of the passed object and appending values in
the same object.
• Therefore, this would produce the following result-
• before change: [10, 20, 30]
• after change: [10, 20, 50]
• Values outside the function: [10, 20, 50]
5. def changeme( mylist1 ):
"This changes a passed list into this function"
mylist1 = [1,2,3,4] # This would assign new reference in mylist
print ("Values inside the function: ", mylist1)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
6. • The parameter mylist is local to the function changeme.
• Changing mylist within the function does not affect mylist.
• The function accomplishes nothing and finally this would produce the following
result-
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
7. Function Arguments
• You can call a function by using the following types of formal
arguments-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
8. Required Arguments
• the arguments passed to a function in correct positional order.
• the number of arguments in the function call should match exactly with the
function definition.
9. # Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme(‘hello’)
Output: hello
10. Keyword Arguments
• related to the function calls.
• the caller identifies the arguments by the parameter name.
• This allows you to
• skip arguments or
• place them out of order
• because the Python interpreter is able to use the keywords provided
to match the values with parameters.
11. def printme( strn ):
"This prints a passed string into this function"
print (strn)
return
# Now you can call printme function
printme( strn = "My string")
12. # Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
13. Default Arguments
• A default argument is an argument that assumes a default value if a value is not provided in the function call for
that argument.
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
14. Variable-length Arguments
• You may need to process a function for more arguments than you specified while
defining the function.
• These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
15. def function_name([formal_args,] *var_args_tuple ):
function_stmt
return [expression]
• An asterisk (*) is placed before the variable name that holds the
values of all non keyword variable arguments.
• This tuple remains empty if no additional arguments are specified
during the function call.
16. printinfo( 10 )
printinfo( 70, 60, 50 )
Output is:
10
Output is:
70
60
50
# Function definition is here
def printinfo( arg1, *vartuple ):
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
17. The Anonymous Functions
• These functions are called anonymous because they are not declared in the
standard manner by using the def keyword.
• You can use the lambda keyword to create small anonymous functions.
• lambda operator can have any number of arguments, but it can have only one
expression.
• It cannot contain any statements and
• it returns a function object which can be assigned to any variable.
18. • An anonymous function cannot be a direct call to print because lambda requires
an expression.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Mostly lambda functions are passed as parameters to a function which expects a
function objects as parameter like map, reduce, filter functions
20. add = lambda x, y : x + y
print add(2, 3)
# Output: 5
21. • In lambda x, y: x + y; x and y are arguments to the function and x +
y is the expression which gets executed and its values is returned as
output.
• lambda x, y: x + y returns a function object which can be assigned to
any variable, in this case function object is assigned to
the add variable.
>>>type (add) # Output: function
22. • The syntax of lambda function contains only a single statement, which is as
follows-
lambda [arg1 [,arg2,.....argn]]:expression
23. # Function definition is here
>>>sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
>>>print ("Value of total : ", sum( 10, 20 ))
>>>print ("Value of total : ", sum( 20, 20 ))
24. Use of Lambda Function
• We use lambda functions when we require a nameless function for a short period
of time.
• In Python, we generally use it as an argument to a higher-order function (a
function that takes in other functions as arguments).
• Lambda functions are used along with built-in functions like filter(), map() etc.
25. filter()
filter(function, iterable)
• creates a new list from the elements for which the function returns True.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output: [4, 6, 8, 12]
26. map()
map(function, iterable)
• It applies a function to every item in the iterable.
• We can use map() to on a lambda function with a list:
>>>M = [1,2,3,4,5]
>>>squaredList = list(map(lambda x: x*x, M))
>>>print(squaredList)
27. Reduce function
reduce(function, iterable)
• applies two arguments cumulatively to the items of iterable, from left to right.
>>>from functools import reduce
>>>list = [1,2,3,4,5]
>>>s = reduce(lambda x, y: x+y, list)
>>>print(s)
• In this case the expression is always true, thus it simply sums up the elements of
the list.
30. Global Vs Local variable
>>>total = 0 # This is global variable.
>>>def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total) return total
# Now you can call sum function
>>>sum( 10, 20 )
>>>print ("Outside the function global total : ", total )
31. • Inside the function local total : 30
• Outside the function global total : 0