Unit III- Functions in
Python
Pranav Gupta
DEFINING LAMBDA FUNCTIONS IN
PYTHON
A lambda function is a concise, unnamed function having they
keyword “lambda” .
lambda arguments: expression
Example: multiply = lambda x, y: x*y.
Python, with its array of functional programming tools, introduces
the concept of lambda functions, which have their roots in lambda
calculus.
Lambda functions, often referred to as "anonymous functions",
deviate from traditional Python functions in that they are not defined
using the standard def keyword, nor do they bear a specific name.
Instead, they embrace a concise approach, realized through the
lambda keyword.
Regular functions and lambda
function
Definition Keyword: Traditional functions employ the def keyword, whereas
lambda functions use lambda.
Naming: While regular functions are named and can be invoked using this
given function name(identifier), lambda functions are inherently anonymous,
often utilized for one-time operations and discarded.
Return Statements: Regular functions may contain the return keyword to
send back results. In contrast, lambda functions automatically return the value
of their lone expression.
Expression Limit: While a standard function might encompass multiple
expressions or statements, lambda functions are restricted to just a singular
expression.
Application: Regular functions are versatile and can handle a plenty of tasks.
Lambda functions, on the other hand, shine in specific situations, such as
when working with functions like map(), filter(), or sorted().
Lambda functions-Advantages
Concise : Their one-liner nature ensures clarity and
enhanced readability in code.
Shortness: Since they're unnamed, they're perfect for
transient use cases where a formal function name might be
overkill.
Anonymous Functions: It can be used when you need a
small, disposable function for a specific task.
LAMBDA FUNCTION EXAMPLE
• Another Example
CLASS IN PYTHON
Class in Python functions as a blueprint or template,
pivotal for the creation of objects.
The fundamental purpose of classes revolves around data
encapsulation. This ensures that data is not only
aggregated but also protected.
A class comprises two main components.
First, we have attributes, which are essentially variables
housed within the class to store data.
Secondly, there are methods, which are functions associated
with the class that outline the feasible operations on its data.
Constructors in Python
Constructors are generally used for instantiating an
object.
The task of constructors is to initialize(assign values)
to the data members of the class when an object of
the class is created.
In Python the __init__() method is called the
constructor and is always called when an object is
created.
Constructors in Python
In python there are two types of constructor:-
default constructor: The default constructor is a simple
constructor which doesn’t accept any arguments. Its
definition has only one argument which is a reference to the
instance being constructed.
parameterized constructor: constructor with parameters is
known as parameterized constructor. The parameterized
constructor takes its first argument as a reference to the
instance being constructed known as self and the rest of the
arguments are provided by the programmer.
Output:-
Object in Python
An object is the core building block of the language, representing
real-world entities or abstract concepts.
Objects are instances of classes defining their structure and
behavior. It is a set of characteristics (variables) and methods
They encapsulate data as attributes and functionality as
methods. Let's understand the objects to model and implement
complex systems in Python and create custom data types and
functionalities.
Slide
11
What is NumPy
NumPy stands for numeric python which is a python package for the computation and
processing of the multidimensional and single dimensional array elements.
Travis Oliphant created NumPy package in 2005 by injecting the features of the ancestor
module Numeric into another module Numarray.
It is an extension module of Python which is mostly written in C.
It provides various functions which are capable of performing the numeric computations
with a high speed.
NumPy provides various powerful data structures, implementing multi-dimensional arrays
and matrices.
These Session
data structures are used for the optimal computations regarding arrays and
29- NumPy Basics-I
matrices.
The need of NumPy
Slide
12
With the revolution of data science, data analysis libraries like NumPy, SciPy,
Pandas, etc. have seen a lot of growth.
With a much easier syntax than other programming languages, python is the
first choice language for the data scientist.
NumPy provides a convenient and efficient way to handle the vast amount of
data.
NumPy is also very convenient with Matrix multiplication and data reshaping.
NumPy is fast which makes it reasonable to work with a large set of data.
Slide
13 Advantages of using NumPy for data analysis
There are the following advantages of using NumPy for data analysis.
a) NumPy performs array-oriented computing.
b) It efficiently implements the multidimensional arrays.
c) It performs scientific computations.
d) It is capable of performing Fourier Transform and reshaping the data stored in
multidimensional arrays.
e) NumPy provides the in-built functions for linear algebra and random number
generation.
• Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the
replacement to MATLAB as Python is more complete and easier programming
language than MATLAB.
Session 29- NumPy Basics-I
NumPy Environment Setup
Slide
14
NumPy doesn't come bundled with Python. We have to install it
using the python pip installer.
Execute the following command.
pip install numpy
It is best practice to install NumPy with the full SciPy stack.
The binary distribution of the SciPy stack is specific to the operating
systems.
Session 29- NumPy Basics-I
Installing Numpy package in idle
Creating a 1D Numpy array
• Output
Creating a Multidimensional (2D)
Numpy array
• Output
NumPy – Arithmetic Operations
NumPy is an open-source Python library for performing array
computing (matrix operations).
It is a wrapper around the library implemented in C and used for
performing several trigonometric, algebraic, and statistical operations.
Python list can be used for array computing, but it is much slower than
NumPy. NumPy achieves its fast implementation.
One of the important features of NumPy arrays is that a developer can
perform the same mathematical operation on every element with a
single command.
LIST TO ARRAY
#CODE: #OUTPUT:
import numpy as np ['books', 'pencils', 'erasers']
arr = ['books', 'pencils', 'erasers'] <class 'list'>
print(arr)
print(type(arr)) ['books' 'pencils' ,'erasers']
print() <class 'numpy.ndarray'>
arr = np.array(arr)
print(arr)
print(type(arr))
NumPy – Arithmetic
• CodeOperations(Addition)
• Outp
ut
NumPy – Arithmetic Operations (Subtraction)
• Code
• Outp
ut
NumPy – Arithmetic Operations (Multiplication)
• Code
• Outp
ut
NumPy – Arithmetic Operations
(Division)
• Code
• Outp
ut
NumPy – Arithmetic Operations (Remainder/ Mod)
• Code
• Outp
ut
NumPy – Arithmetic Operations
• Code
(Exponent)
• Outp
ut
ARRAY MATHEMATICS
ARITHMETIC OPERATIONS:
np.add(10, 20) #Addition
np.subtract(10, 20) #Subtraction
np.multiply(10, 20) #Multiplication
np.divide(10, 20) #Division
np.exp(10) #Exponentials
np.sqrt(10) #Square Root
np.sin(10) #Sine value
np.cos(10) #Cosine value
np.log(10) #Logarithmic value
COMPARISION OPERATIONS:
arr1= np.array([1, 2, 3])
arr2= np.array([1, 4, 3])
np.array_equal(arr1, arr2)
COPYING ARRAYS
Working with arrays has been made easy
using NumPy.
An array can be copied using a function called
copy().
EXAMPLE:
arr = np.array([1, 2, 3, 4])
arr_copied = np.copy(arr)
print(arr_copied)
SORTING ARRAYS
To sort an array is to put its elements in a particular order.
These orders can range from increasing to alphabetical.
To sort an array using NumPy, use the sort() function.
EXAMPLE:
import numpy as np
arr = np.array([1, 2, 3, 6, 4, 8, 5, 9])
arr_sorted = np.sort(arr)
print(arr_sorted)
SUBSETTING
Subsetting refers to the method in which the
index of the element is specified in a square
bracket notation ([]).
EXAMPLE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
print(arr1[1]) #OUTPUT: [6, 7, 8]
print(arr2[0,1]) #OUTPUT: 4
SLICING
Slicing in NumPy can be referred to as the method in
which uses the slice notation (:) to retrieve an
element/element from a list(row or column values).
EXAMPLE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
print(arr1[0:2]) #OUTPUT: [[1 2 3] [6 7 8]]
print(arr2[0:3,1]) #OUTPUT: [ 4 10]
INDEXING
Indexing is the process of using advanced
parameters to retrieve an element/element
from a multidimensional list.
There are two types of indexing, Boolean and
fancy.
Boolean Indexing is the type of indexing in
which we use a logical statement to retrieve an
element/element from a multidimensional list.
The logical statement inside the condition must
return True or False.
EXAMPLE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
print(arr1[arr1 > 3]) #OUTPUT: [6, 7, 8]
Fancy Indexing is quite similar to Boolean Indexing.
The only difference is that in fancy indexing, the indices
of the elements that are to be retrieved can be
specified.
EXAMPLE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12], [1, 2, 3]])
print(arr2[[0, 2], [2, 1]])
#OUTPUT: [ 6 2]
ARRAY MANIPULATION
ADDITION AND DELETION OF ELEMENTS:
To add/delete an element from an array, we use the
append() and delete() functions, respectively.
The append() adds an element at the end of a list,
whereas the delete() function deletes a specific
element.
EXAMPLE:
print(np.append(arr1, arr2))
np.delete(arr, 2)
INSERTING AN ELEMENT AT A PARTICULAR INDEX
With the help of insert() in NumPy, an element can be
inserted at any specific position in an array.
EXAMPLE:
print(np.insert(arr, 2, 10))
CHANGING THE SIZE OF THE ARRAY
To change the shape of an array, we can use the resize() and
reshape() functions.
The ravel() function allows us to flatten a multidimensional
array into a one-dimensional list.
#CODE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
#resize() #Output
[[1 2]
print(np.resize(arr1, (3, 2)))
[3 6]
[7 8]]
#reshape() #Outp
ut
print(np.reshape(arr2, (3, 2))) [[ 2 4]
[ 6 8]
[10
#ravel() 12]]
print(np.ravel(arr2)) #OUTPUT: [ 2 4 6 8 10 12]
Key differences
Reshape Resize
The reshape attribute throws In the case of reshape
a ValueError if the array is not attribute, it adds 0s to fill
divisible into the specified the array such that it is
number of sub arrays. Value exactly divisible into the
error is observed whenever number of fragments
the array lacks enough mentioned by the user.
elements.
In the case of reshape() a
The resize() method uses
copy of the existing array is
created and the change in in-place modifications and
dimensions are made to the so the original array gets
copy of the array. Thus there overwritten.
is no change in the
Transpose of an array
A matrix created by switching the number of rows and columns
amongst themselves is called the transpose of a matrix.
The transpose() is provided by NumPy.
EXAMPLE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
print(arr1)
print(np.transpose(arr1))
COMBINING ARRAYS
In NumPy, we can combine two or more two arrays in
three ways; hstack(), vstack() and concatenate().
hstack() allows us to combine two arrays in a
horizontal sense, vstack() combines two arrays in a
vertical sense, and concatenate() combines
elements row or column-wise(default axis is 0(row-
wise)).
#CODE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
print(np.hstack((arr1, arr2)))
print(np.vstack((arr1, arr2)))
print(np.concatenate((arr1, arr2), axis=1))
#OUTPUT:
[[ 1 2 3 2 4 6]
[ 6 7 8 8 10 12]]
[[ 1 2 3]
[ 6 7 8]
[ 2 4 6]
[ 8 10 12]]
[[ 1 2 3 2 4 6]
[ 6 7 8 8 10 12]]
SPLITTING AN ARRAY
Using NumPy, we can easily split an array into any number of
parts using the split() function.
The split() function takes in two arguments; the array to be split
and the number of partitions we want.
EXAMPLE:
import numpy as np
arr1 = np.array([[1, 2, 3], [6, 7, 8]])
arr2 = np.array([[2, 4, 6], [8, 10, 12]])
#Splitting arr1 into two sub-arrays:
print(np.split(arr1, 2))#[array([[1, 2, 3]]), array([[6, 7, 8]])]
DATETIME MODULE
DateTime module is provided in Python to work with dates and times.
In python DateTime, is an inbuilt module rather than being a primitive
data type.
SYNTAX:
import datetime
var1 = datetime.date(YYYY, MM, DD)
#This will convert the numeral date to
the date object
EXAMPLE
#CODE:
import datetime
userdate = datetime.date(2021, 10, 20)
print('userdate: ', userdate)
print('type of userdate: ', type(userdate))
#OUTPUT:
userdate: 2021-10-20
type of userdate: <class 'datetime.date'>
This class helps to convert the numeric date & time
attributes to date-time format in the form of YYYY-MM-
DD hr:min:s:ms.
SYNTAX:
import datetime
var1 = datetime.datetime(YYYY, MM, DD, hr, min, s,ms)
EXAMPLE
#CODE:
import datetime
userdatetime = datetime.datetime(2019, 5, 10, 17, 30, 20,
154236)
print('userdatetime: ', userdatetime)
print('type of userdatetime: ', type(userdatetime))
#OUTPUT:
userdatetime: 2019-05-10 14:30:20.154236
type of userdatetime: <class 'datetime.datetime'>
PSEUDO RANDOM NUMBER
Pseudorandom numbers are a collection of
partially random numbers, as the name implies.
Despite appearing random, they are not.
In other terms, a pseudo-random number is a
random number that was produced by a computer.
If the beginning of the series is known, many
numbers are created quickly and can also be
repeated later.
As a result, pseudo-random numbers are accurate
GENERATE RANDOM INTEGER
To generate a random integer, we use the random
module from NumPy.
Using the numpy random randint() function, a random
integer can be generated from a range of 0 to n.
EXAMPLE:
import numpy as np
random_number = np.random.randint(12)
print(random_number)
GENERATE RANDOM FLOAT
To generate random float values, we use the rand() function
provided by the numpy.random() module in NumPy.
The rand() function returns a float value that lies between 0
and 1.
EXAMPLE:
import numpy as np
random_float=np.random.rand()
print(random_float)
GENERATE RANDOM ARRAY
Use the numpy.random() module to generate an array
consisting of random integers.
To do this, use the numpy random randint() function and add
a parameter defining the size of the array.
EXAMPLE:
import numpy as np
arr=np.random.randint(20, size=(4))
print(arr)
Generate a Random Array of Floats
To generate an array of random floats, simply use
the random() function with a parameter that
specifies the size of the array.
EXAMPLE:
import numpy as np
arr=np.random.rand(4)
print(arr)
GENERATE A RANDOM NUMBER
FROM THE ARRAY
Use the numpy random choice()
function.
NumPy random choice() is a function that
enables us to generate a random value
from an array of data, regardless of the
types of those values.
Since it's a part of the numpy.random()
module, use it with the numpy.random()
function.
EXAMPLE
#CODE:
import numpy as np
random_choice = np.random.choice([1, 2, 4, 5])
print(random_choice)
#OUTPUT:
4
MODULE VS LIBRARY VS PACKAGE