DSP Notes
Data Structure Using Python
Unit no. 1
Introduction and Control Flow statements in Python
➢ Data Def -
Anything that has some meaning or fact is considered as data. It can be in various form.
such as video, audio, file, etc.
➢ Data Structure Def -
Data Structure is an arrangement/way of storing data items that consider not only the elements stores but
only also their relationship to each other.
➢ Pre-requests?
→ Python (Variable, indentation, operators, in-built data types, OOPs)
→ Time and Space Complexity
→ Improves problem solving skills.
→ Efficient Programming
→ Campus Placement.
➢ Python -
→ Python is high level programming language and interpreted language.
→ Known for its simple syntax that makes it best choice for beginner.
#Application
• Used for app development, Web development, data analysis, Data Science, AI ML, etc.
➢ First Python -
Program:- print("Hello World")
• String always written in (" ") double Quotation.
• We use parenthesis ().
• print is a function that is used to invoke.
O/P: Hello World
# To comment or uncomment
Ctrl + / -> Shortcut
// -> Symbol
# Variable?
e.g.
a = 2.2
a = "Ram"
a=2
Here a = variable,
b = values
Variable is like a Container that stores value in it.
# Rule for naming a variable -
• Starts with letter, underscore(_), $ sign.
• It do not contain space. -Ingle P.
Ex. Studentname ✓
Student name ✗
Student_name ✓
Student$name ✓
student@name✗
• Variable is Case Sensitive.
Ex.
Age = 20
age = 20
AGE = 20
• Do not use reserved Keywords.
Ex. If, while, else, do, while
E.g. If = 2 ✗
➢ Indentation -
Indentation is used to maintain the structure of program or core.
➢ Data types -
• We required data type to store different types of values in memory.
• Data type is a specified type of value that a variable can store.
• It is required to perform operations.
a = 2 → int ]
a = 2.2 → float ]-> Data types
a = "Ram" → String ]
a=2
b=2
print (a+b)
Output:-
4
a = "2"
b = "2"
print (a+b)
Output:-
22
➢ Operators :-
Operators is a special symbol that perform operation on operands (Variable or values). Python has 7 main
types of operators:
1) Arithmetic (addition, subtraction, Multiplication, div, etc)
2) Comparison (>, <, <=, >=, !=, ==)
3) Logical (AND, OR, NOT)
4) Assignment (+=, -=, *=, etc.)
5) Bitwise (XOR, NOR)
6) Identification (is, is not)
7) Membership (in, in not)
Q] Create a calculator which is capable of performing add, sub, multi, division. Operations on values :-
a = int(input("Enter your first number"))
b = int(input("Enter your second number"))
Print("The sum of two values are:", a+b)
Print("The sub of two values are:", a-b)
Print ("The multi of two values are:", a*b)
print(" The divi of two values are:", a/b)
➢ Typecasting
The Conversion of one datatype to another datatype is Called Typecasting. Python supports a wide variety of
function of all methods like -
int ()
float ()
str ()
list ()
dict(), etc.
1) Explicit conversion
2) Implicit conversion
Explicit
The conversion of one datatype into another datatype done by a programmer, developer or user manually
as per requirement.
IMPLICIT
Datatype in Python do not have the same level. Some datatype has high order or level and some have lower
level. While performing operation on 2 variables then lower level converts into higher level variable.
Example :- c = 1.9 → float (higher)
b = 8 → lower
Print (c+b)
o/p = 9.9 → float
➢ How to take user input:-
R = input(“Enter your name”)
Print(“Your name is:”, R)
➢ String:-
In Python Anything that is written in double(“………”) or single quote (‘…………’) is called String.
e.g. name = "Ram"
➢ Indexing:-
name = “Ram”
print (name [0])
print (name [1])
print (name [2])
O/P - R
a
m
|R|a|m|
|0|1|2 |
➢ Functions or Method Performed or string:-
[Link]
name = "Ram"
Print (len(name))
O/P:- 3
[Link]
a = "Ram"
Print ([Link]())
O/P:- RAM
3. Lower
a = "Ram"
print ([Link]())
o/p = ram
4. To Capitalize
a = "i love india"
Print([Link]())
O/P:- I love INDIA.
5. Count
a = "siddhi"
print ([Link]("d"))
O/P:- 2
6. Swap Case
a = "Jiya"
print([Link]())
O/P:- jIYA
➢ Conditional Statement
Conditional Statement is a programming statement that allows program to make decision based on a
condition whether the condition is True or False.
It is also called decision-making statement.
Conditional Statement includes:-
① If
② If - else
③ If - elif
④ Nested if
① If - else Statement/Control flow Statement
a = int (input("Enter your age:"))
Print ("Your age is: ", a)
If (a > 18):
print ("You can drive")
else:
print("You cannot drive")
② Elif condition (used for multiple condition)
num = int (input ("Enter the value of your number: "))
If (num < 0):
print ("Number is negative")
elif (num == 0):
print("Number is zero")
else:
print ("Number is positive")
③ Nested if statement:
When one if is inside another if is Called Nested if.
num = 1
if num < 0:
print("number is negative")
elif num > 0:
if num <= 10:
print("number is in between 1 to 10")
elif num <= 20:
print("number is between 11 to 20")
else:
print("num is greater than 20")
else:
print("num is zero")
➢ Loops:-
Sometimes a programmer wants to execute a group of statements in a certain number of times. This can be
done using loop.
① For Loop :-
for String:-
name = "Ram"
for i in name:
print (i)
O/P: R
a
m
for list
colors = ["red", "green", "blue"]
for color in colors:
print (Color)
for i in color:
print(i)
O/P:- red
r
e
d
green
g
e
e
n
:
:
#Range
→ Range Generates a sequence of numbers.
→ Index [start, stop, step]
Generates a sequence of numbers.
① for k in range (5):
Print (k)
O/P: 0
1
2
3
4
② for k in range (1, 9):
print (k)
O/P: 1
2
3
4
5
6
7
8
③ for k in range (1, 201):
print (k)
→ O/P: 1 to 200
④ for k in range (1, 12, 3):
prints (K)
→1
4
7
10
② While loop:- (Works on Condition)
while loop runs until the condition is satisfied.
i=0
while (i < 3):
print(i)
i=i+1
O/P: 0
1
2
i=0
while (i <= 3):
print (i)
i=i+1
→ O/P: 0
1
2
3
➢ Break and Continue :-
Q) Print the multiplication table of 5 using break statement.
1. Break: ( leave the loop)
for i in range(12):
if (i == 10):
break
print("5x", i+1, "=", 5 * (i+1))
O/P:-
5x1 = 5
5x2 = 10
5x3 = 15
...
5x10 = 50
2. Continue: (skip the iteration)
for i in range (12):
if (i == 10):
Continue
print("5x", i, "=", 5*i)
O/P:-
5x0 = 0
5x1 = 5
5x2 = 10
...
5x9 = 45
5x11 = 55
➢ Difference between for loop and while loop:-
For loop:
When we want to repeat code for every item in a sequence, then we use for loop.
While loop:
When we want to repeat code as long as the condition is met, then we use while loop.
Unit no. 2
Python specific Data Structure and functions
➢ In-built data types in python:-
List:
• List are ordered collection of data items.
• They store multiple items in a single Variable.
• List items are Separated by Commas and enclosed within [] Square bracket.
• List are changeable or mutable, meaning we can alter their elements of list after creation.
• The elements of list can access by index, which starts from 0.
Ex1: List 1 = [1, 2, 3, 4, 5]
Print (List 1)
O/P: [1, 2, 3, 4, 5]
Ex2: List 2 = ["Red", "Green", "Blue", "Pink"]
Print (List 2)
O/P: ['Red', 'Green', 'Blue', 'Pink']
EX3: marks = [3, 5, 6, "Riya", True]
print (marks) # [True = Boolean datatype (True, False)]
print (type (marks))
print (marks [0])
O/P: [3, 5, 6, 'Riya', True]
<class 'list'>
3
As we can see in example 3 a single list can contain items of different data type.
➢ Negative index:
0 1 2 3 4
marks = [3, 5, 6, "Riya", True]
print (marks [-3]) # Negative indexing → O/P 6
print (marks [len (marks) - 3]) # Positive indexing → o/p 2
print (marks [5 - 3]) → O/P 2
print (marks [2]) → O/P 6
➢ Check whether item is present in a list:
Ex 1:
marks = [8, 9, 3, 4]
if '2' in marks:
print ("Yes")
else:
print ("No")
O/P: 'No'
Ex 2:
a = [8, 9, 'Riya', 10, 12]
if 'Riya' in a:
print ("Yes")
else:
print ("No")
O/P: 'Yes'
Ex 3:
a = ['Ram', 2, 3]
if 'am' in 'Ram':
Print ("yes")
else:
print ("No")
O/P: "Yes"
➢ Jump Index:
Ex. a = [1, 2, 3, 4, "Riya", 10, 5, 2]
print (a[1:5]) → O/P: [2, 3, 4, 'Riya']
print(a[1:5:2]) → O/P: [2, 4]
Syntax: [Link] [start: end: jump index]
➢ List Comprehension:
It is a Short and concise way to create a list. It combines for loop and optional condition into a single line.
Ex 1: List = [i for i in range (4)]
print (List)
O/P: [0, 1, 2, 3]
Ex 2: list = [i*i for i in range (10)]
print (list)
O/P : [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Ex 3: list = [i*i for i in range (10) if i/2==0]
print (list)
O/P: [0, 4, 16, 36, 64] → even numbers
➢ Methods applied on list:
① Append: It add the new element at the end of the list. e.g. →
l = [1, 2, 3, 4]
print(l)
[Link] (5)
print (l)
O/P: [1, 2, 3, 4, 5]
② Sort Method: It Sort the elements in ascending order. e.g. →
l = [13, 14, 6, 3, 2, 0, 1]
[Link]()
print (l)
O/P: [0, 1, 2, 3, 6, 13, 14]
③ Sort Method for descending order: It Sort the elements in descending order.
l = [13, 14, 6, 3, 2, 0, 1]
[Link] (reverse = True)
print (l)
O/P: [14, 13, 6, 3, 2, 1, 0]
④ Reverse method: It is use to sort the elements in reverse.
l = [0, 1, 2, 3, 4, 5]
[Link]()
print(l)
O/P: [5, 4, 3, 2, 1, 0]
⑤ Index Method: It tell the index of given element. e.g.
l = [0, 1, 4, 6, 9]
print ([Link] (4))
O/P : 2
⑥ Count Method: It count the number of given elements. e.g.
l = [1, 2, 4, 6, 1, 5, 1]
print ([Link] (1))
O/P: 3
⑦ Copy Method: It Copy the elements as it is, without any changes.
l = [2, 4, 6, 7, 9]
print (l)
m = [Link]()
print(m)
O/P: [2, 4, 6, 7, 9]
[2, 4, 6, 7, 9]
⑧ Insert method: It add a new element into the list by giving index number. e.g. →
l = [2, 4, 6, 7]
print (l)
[Link] (0, 899) #(Here, 0 = Index & 899 = Element)
print (l)
O/P : [899, 2, 4, 6, 7]
⑨ Extend Method: It is use to combine two list into a single list. e.g. e.g.→
l = [3, 2, 4, 6]
m = [20, 30]
[Link] (m)
print (l)
O/P: [3, 2, 4, 6, 20, 30]
⑩ Concatenate: Same as extend but with different method.
l = [2, 4, 6]
m = [3, 2, 1]
k=l+m
print(k)
O/P: [2, 4, 6, 3, 2, 1]
➢ Tuples:
• Tuples are ordered collection of data items.
• They store multiple items in a single variable.
• Tuples items are separated by commas and enclosed within (..) round brackets.
• Tuples are unchangeable that means we cannot alternate them after creation.
e.g.
tup = (1, 5, 6)
print (type (tup))
O/P : <class 'tuple'>
Example:
1. tup = [5, 4, 3, 2, 1] → list
tup [0] = 90
O/P: [90, 4, 3, 2, 1]
2. tup = (5, 4, 3, 2, 1) → tuple
tup [0] = 90
O/P: error
we cannot change any value of index in tuple
3. tup = (1, 2, 76, 342, 32, "green", True)
print (type(tup))
print (tup[0])
print (tup[1])
print (tup[2])
print (tup[30])
O/P:<class 'tuple'>
1
2
76
342
#Negative indexing
[Link] = (20, 30, 40, 50)
print (len (tup)) → O/P: 4
print (tup [0]) → O/P:20
print (tup [-1]) → O/P:50
print (tup [-2]) → O/P:40
#To check whether an element present in tuple or not
5. tup = (4, 3, 2, 1)
if 3 in tup:
Print ("yes")
else:
print ("No")
tup2 = tup [1:4]
Print (tup 2)
O/P: Yes
(3, 2, 1)
Tuples are immutable / unchangeable. Hence, if you want to add, remove or change tuple items then you
must convert the tuple to a list. Then perform operation on that list and convert it back to tuple.
As tuple is unchangeable collection of elements so it has limited built in method.
1) Count Method ()
tuple 1 = (0, 2, 4, 2, 6, 2, 8, 2)
a = tuple 1. count(2)
print ("Count of 2 in tuple 1 is: ", a)
O/P: Count of 2 in tuple 1 is 4
2) Index Method
The Index Method returns the 1st occurrence of the given element from the tuple. If the element is not
found in the tuple, then it raises an error.
Syntax:
[Link] (element, start, end)
tuple1 = (0, 1, 2, 13, 2, 13, 1, 13, 2)
a = [Link] (13)
print("First occurrence of 13 is: ", a)
O/P: 3 → index
➢ Sets:
• Sets are Unordered collection of data items.
• They store multiple items in a single variable.
• Set items are separated by Comas and enclosed within {} Curly braces.
• Sets are unchangeable or mutable means we can change items of the sets once created.
• Sets do not contain duplicate items.
• Sets can store values of different data type.
like a = {'Riya', 2, 4, 6, 'True'}
• Sets does not maintain Order. e.g.
a = {2, 4, 3, 6}
Print (a)
O/P:- {4, 3, 6, 2}
• Sets do not support indexing or slicing.
o Accessing Set items:
We can access items of set using for loop. e.g.
info = {"Riya", 6, False, 2.6, 6}
for item in info: print(item)
O/P: False
Riya
2.6
6
o Methods of Sets:
Set in Python work in more or less same way as Sets in mathematics, like we can perform operation like
Union & intersection on the set just like mathematics.
1) Union ()
The Union method prints all items that are present in 2 Sets. The union method returns a new Set. e.g.
s1 = {1, 2, 5, 6}
s2 = {3, 6, 7}
print([Link] (s2))
O/P: {1, 2, 3, 5, 6, 7}
2) Intersection ()
The Intersection method prints only items that are Similar to both sets. The Intersection method returns
Only items that are present in both sets. e.g. →
cities = {"Tokyo", "Mumbai", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Berlin", "Kabul", "Madrid"}
cities3 = [Link] (cities2)
print (cities3)
O/P: {"Tokyo", "Berlin"}
3) Symmetric difference
This method prints only items that are not common in both sets. e.g.
flower = {"Lotus", "Rose", "Sunflower"}
flower2 = {"Rose", "Lily", "Marigold"}
flower3 = [Link] (flower2)
print (flower3)
O/P: {"Lily", "Sunflower", "Lotus", "Marigold"}
4) Difference ()
This method prints only items that are present in original set.
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
cities3 = [Link] (cities2)
print (cities3)
O/P: {"Madrid", "Berlin", "Tokyo"}
5) Issuperset ()
The issuperset method checks if all the items of a particular set are present in the Original Set. It returns
true if all items are present, else it returns false.
e.g.
color = {"Yellow", "red", "brown"}
color2 = {"Yellow", "brown"}
print ([Link] (color2))
O/P: True
6) Issubset ()
This method checks if all the items of original set are present in the particular set, it returns true if all items
are present, else it returns false.
color = {"Blue", "Black", "Red"}
color2 = {"Yellow", "Pink", "Blue"}
print ([Link] (color2))
O/P: False
7) add ()
If you want to add a single item to the original set use add method.
e.g. →
letter = {"A", "B", "D", "F"}
[Link] ("Z")
print (letters)
O/P: {'A', 'B', 'D', 'Z', 'F'}
8) Remove () / Discard ()
We can use it to remove items from set and list.
The main difference between remove & Discard is that if we try to delete an item which is not present in set
then remove raise an error, whereas discard does not raise any error.
Example:
# Remove
e.g. 1
letter = {"A", "B", "D", "F"}
[Link] ("A")
print (letters)
O/P :- {'B', 'D', 'F'}
e.g. 2
colours = {"Red", "Pink"}
[Link] ('blue')
print (colours)
O/P :- Key error
#Discard
e.g. 3
colours = {"Red", "Pink"}
[Link] ('blue')
print (colours)
O/P: {'Red', 'Pink'}
➢ Dictionary:
Dictionaries are ordered collection of data items. They store multiple items in a single variable. Dictionary
items are (key - value pairs) that are Separated by colons (:) and enclosed within curly braces {}.
eg.1 → a = {‘Name’: "Raj"} Here Name = key, Raj = value.
eg.2 → dict = {'Riya': human, 'cat': animal, 'Lily': Flower}
print(dict ["cat"])
O/P :- animal
Key → 'cat'
Value → animal
➢ Accessing dictionary items:
1) Accessing Single Value:
Values in a dictionary can be access by mentioning key name in a square Bracket or by using get method.
e.g.
info = {'name': 'Karan', 'age': 19, 'eligible': True}
print (info['name']) → (it will throw an error if key does not exist)
print ([Link]('eligible')) → (it will print None)
O/P: Karan
True
2) Accessing multiple values:
We can print all the values in dictionary using values() method.
e.g.
info = {'name': 'Karan', 'age': 19, 'eligible': True}
print([Link]())
O/P: dict_values(['Karan', 19, True])
3) Accessing multiple keys:
We can print all the key in the dictionary using keys() Method. e.g. →
info = {'name': 'Karan', 'age': 19, 'eligible': True}
print ([Link]())
O/P :- dict_keys(['name', 'age', 'eligible'])
4) Accessing key - value pairs:
We can print all the key-value pairs in the dictionary using items () method.
e.g. →
info = {'name': 'Karan', 'age': 19, 'eligible': True}
print ([Link] ())
O/P: dict_items([('name', 'Karan'), ('age', 19), ('eligible', True)])
➢ Functions in Python:
Function is a block of code that performs specific tasks. It is defined using "def" keyword, instead of writing
same code again and again we create a function once and can be called whenever needed.
Syntax: def function_name (a, b) [a & b are Parameters which are optional]
Ex. 1:
def greet():
print ("Hello, Python")
greet ()
O/P: Hello, Python
Ex. 2:
def Calculatemean (a, b):
mean = (a*b)/(a+b)
print (mean)
a=9
b=8
O/P: 4.2352941………
o Types of function
① Built-in function
It is already pre-coded in Python
Ex: name = "Python"
print(len(name))
O/P: 6
E.g. max(), min(), sum(), len(), avg(), set(), list()
② User-defined function
This are created by user or programmer as per their requirement.
Ex: def message ():
print ("Python is simple")
message ()
O/P : Python is simple.
o Calling a function:
We Call the function by giving function name followed by parameters (if any) in the parenthesis.
ex: def name (fname, lname):
print ("Hello,", fname, lname)
name ("Sam", "Wilson")
O/P :- Hello, Sam Wilson
o Function Arguments:
There are 4 types of arguments that we can provide in a function.
1) Default Argument.
2) Keyword Argument / Order Argument.
3) Variable length Argument
4) Required argument.
① Default Argument:
Ex. def average (a=9, b=1):
print("The average is:", (a+b)/2)
average ()
O/P: 5
② Order Argument :
Ex. def average(a, b):
print("The average is:", (a+b)/2)
average(b=21, a=9)
O/P: 15.0
③ Variable length argument: It always passing a flexible no. of using (* arys)
def average (* numbers):
total = 0
for i in numbers:
total += i
Print ("Average is:", total / len(numbers))
average (5, 6)
O/P: 5.5
④ Required argument
Ex. def average(a, b):
print("The average is", (a+b)/2)
average(4, 6)
O/P: 5.0
➢ Scope of Variables:
Variable: A Variable is a named location in memory that stores values. In Python, we can assign a value to a
variable using the assignment operator.
x=5
y = "Hello world"
There are 2 types of variables:
① Local Variable
A Local Variable is a variable that is defined within a function and is only accessible within that function. It is
created when the function is called and it is destroyed when the function returns.
Ex:
x = 10
def display():
print (x)
display()
O/P: 10
Here, access local variable because it is created in function.
② Global Variable
A Global Variable is a variable that is defined outside a function and accessible from any function in the
entire code.
EX. 1
def display():
x = 10
display()
print (x)
O/P: Name error: x is not defined because x is available outside the function
Ex. 2
x = 50 # Global variable
def display ():
print (x)
display()
print (x)
O/P: 50
50
➢ The global Keyword:
It is used to declared that a variable is a global variable, and should be accessed from the global scope.
Ex 1.
x = 10
def change ():
global x
= 20
change ()
print (x)
O/P : 20
Ex. 2.
x = 10 # global variable
def my_function ():
global x
x = 5 # This will change the value of global variable x
y = 5 # local variable
my_function ()
print (x) # prints 5
print (y) # This will cause an error because y is a local variable and is not accessible outside of the function.
Unit no. 3
Python Modules & Packages
➢ Modules in Python:
A module is a Python file (.py) that contains reusable code like functions, variables and classes. Instead of
writing the same code again and again, we can create a module and use it whenever required.
Ex. Create a filename my_module.py
def greet():
print("Hello, Python")
greet ()
→ Here my_module.py is a module.
→ we can use this module in another program.
Ex. Import my_module
my_module.greet ()
O/P: Hello, python
o Advantages of modules:
1) Code reusability
2) Reduces code duplication.
3) Makes program easier to manage.
4) Improves readability.
o Writing Modules:
Creating our own python file containing functions, variables or class is called Writing a Module.
Ex: Create a file [Link]
def add (a,b):
return a+b
def sub (a,b):
return a-b
→ This file act as a module
Using this module:
import calculator
print([Link] (10, 5))
print ([Link] (10, 5))
O/P: 15
5
o Importing Module:
Importing a module means bringing the code of one module into another Python program, so that we can
use its function and variables.
Syntax: import module_name
Ex: import math
print ([Link] (25))
O/P : 5
Here, math is a built-in Module.
o Different ways of Importing Modules:
Syntax: import module_name
import math
print ([Link]())
O/P: 3.14159………….
o Import with alias
We can give a short name to a module using as alias
Syntax: import module_name as alias
import math as m
print ([Link](25))
O/P: 5
o Import a specific object from module:
Instead of importing complete module we can import only required functions.
Syntax: from module_name import [Link]
Ex: from math import sqrt
print (sqrt (25))
O/P: 5
o Importing Objects from module:
Importing only specific functions, classes or variable from a module is called importing objects from
modules.
Ex: from math import pi
print (pi)
O/P: 3.1415....
Here, math is module & pi is object imported for module.
o Python built-in modules:
Built-in modules are pre-written modules provided by python. We dont need to create them. We can
directly import and use them.
EX.
Module | Purpose
math | Mathematical operations
random | Generate random numbers.
datetime | data & time operations.
statistics | Used for statistical calculations.
os | Operating System functions
o Numeric and Mathematical module:
* (Math module): *Math()
Provides mathematical functions.
Ex.
Import math
sqrt()
It returns square root.
* (factorial Module):
factorial () → Returns factorial of the number.
from math import factorial
print (factorial (5))
O/P: 120
* pow () → Returns power value
print ([Link] (2, 3))
O/P: 8
* Ceil () → Rounds number upward
print ([Link] (4.2))
O/P: 5
* floor () → Rounds number downward.
print ([Link] (2.9))
O/P: 2
• Functional programming Module:
Python provides modules that support functional programming.
The main module is functools module. It provides functions used for functional programming.
Syntax: import functools
Important function of functools:
1) Reduce () → applies a function repeatedly on elements of a Sequence and returns a Single value.
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce (lambda x, y: x+y, numbers)
print (result)
O/P: 10
2) Partial ()
A partial function is created by fixing one or more arguments of an existing function, so the new function
requires fewer arguments.
EX.
from functools import partial
def multiply(a, b):
return a * b
double = partial(multiply, 2)
print(double(5))
o/p: 10
➢ Python Package
A package is a collection of multiple modules store together in a Single directory. In simple word module = 1
python file (.py). Package = Collection of many python modules
Ex. A Package named Student may contain:
Student (Package)
├── [Link]
├── [Link] -> (Modules)
└─ [Link]
o Need of Python Packages:
1) Organized Code - Large programs can be divided into smaller modules.
2) Reuse Code - A package can be used in multiple projects.
3) Avoid naming Conflict - Different packages can have modules with the same name.
Ex. [Link], [Link] -> both can have a module name student.
4) Easy maintenance - Managing large applications becomes easier.
o Structure of a python package:
A basic python package may contain:
My_package
├── __init__.py
├── [Link]
└── [Link]
* __init__.py file:
It is a Special file inside folder that tell python that the folder is a Package. It can contain initialization code.
Math_package
├── __init__.py
├── [Link]
└── [Link]
o Installing Python Package:
Installing a package means downloading and adding external packages to your Python environment, so that
you can use them.
Python uses a tool called "pip" for installing packages.
o Python package installer (pip):
pip is a package management System used to install and manage python packages. It comes automatically
with python installation.
Syntax: pip install package_name
Ex: Installing numpy
pip install numpy
After installation import numpy.
Now numpy can be used in program.
o Commonly used Python packages:
Package | Purpose
numpy | Used for numerical calculation
pandas | Data analysis
matplotlib | Data Visualization
scikit-learn | Used in Machine learning
requests | Working with web request
o Checking installed packages:
To see installed packages we write:
pip list
O/P: numpy, pandas, matplotlib, etc.
o Uninstalling packages:
To remove a package:
pip uninstall package_name
Ex: pip uninstall numpy
o Writing Python packages:
Creating our own Python package by organizing python module into a folder is called Writing a python
package.
*Steps to create a package*
Step 1: Create a folder
Step 2: Create __init__.py
Step 3: Add modules.
e.g. Calculator
->[Link]
def add (a, b):
return (a+b)
->[Link]
def sub (a, b):
return (a-b)
o File Structure:
Calculator (package)
├── __init__.py
├── [Link] -> {Modules/Files}
└── [Link]
o Using our own package:
Suppose we want to use addition module from calculator:
from [Link] import add
print (add (10, 5))
O/P: 15
o Difference between module and package:
Module | Package
1) Single python file. | 1) Collection of modules containing modules.
2) Extension is .py | 2) Folder
3) Smaller program component. | 3) Used for larger projects
4) Eg. [Link] | 4) Eg. numpy, pandas.
o Using Standard Numpy: (Numerical Python)
Numerical Python is a powerful python library used for performing calculation efficiently. It provides a data
Structure called Numpy array (ndarray).
->To use numpy:
import numpy as np
np → alias (short name)
o Important methods in Numpy:
① [Link]()
■ Purpose: Use to create a numpy array from list or tuple.
■ Syntax : [Link] (object)
Ex: import numpy as np
a = [Link] ([1, 2, 3, 4])
print (a)
O/P: [1 2 3 4]
② [Link]()
■ Purpose: It creates an array filled with zeros.
■ Syntax : [Link] (shape)
Ex : a = [Link] (5)
print (a)
O/P : [0. 0. 0. 0. 0.]
③ [Link]()
■ Purpose: It Creates an array filled with ones.
■ Syntax: [Link] (shape)
Ex : a = [Link] (4)
print (a)
O/P : [1. 1. 1. 1.]
④ [Link] ()
■ Purpose: It creates an array with a sequence of numbers.
■ Syntax: [Link] (start, stop, step)
Ex : a = [Link] (1, 10, 2)
print (a)
O/P: [1 3 5 7 9]
⑤ [Link]()
■ Purpose: It Creates equally spaced number between 2 values.
■ Syntax: [Link] (start, stop, number)
Ex: a = [Link](0, 10, 5)
print (a)
O/P: [0, 2.5, 5, 7.5, 10.]
⑥ [Link]()
■ Purpose: It returns the size or dimensions of an array.
■ Syntax: [Link] (array)
Ex: a = [Link] ([[1, 2, 3], [4, 5, 6]])
print ([Link])
O/P: (2, 3) → 2 rows, 3 columns
⑦ [Link]()
■ Purpose: Returns the number of dimensions of an array.
■ Syntax: [Link] (array)
Ex : a = [Link] ([1, 2, 3])
print ([Link])
O/P: 1
⑧ [Link] ()
■ Purpose: Returns the total no. of elements.
■ Syntax: [Link] (array)
Ex : a = [Link] ([[1, 2], [3, 4]])
print ([Link])
O/P: 4
⑨ [Link]()
■ Purpose: It changes the shape of array without changing the data.
Ex.: a = [Link] ([1, 2, 3, 4, 5, 6])
b = [Link] (2, 3)
print (b)
O/P: [[1 2 3]
[4 5 6]]
⑩ [Link] ()
■ Purpose: Used to combine 2 or more arrays
Ex: a = [Link] ([1, 2, 3])
b = [Link] ([4, 5, 6])
c = [Link] ((a, b))
print (c)
O/P: [1 2 3 4 5 6]
⑪ [Link]()
■ Purpose: It Splits an array into smaller arrays.
Ex: a = [Link] ([1, 2, 3, 4])
print ([Link] (a, 2))
O/P: [array([1, 2]), array([3, 4])]
⑫ Mathematical Methods
a) [Link]()
a = [Link] ([1, 2, 3])
print ([Link] (a))
O/P: 6
b) [Link]()
print ([Link] ([10, 20, 30]))
O/P: 20
c) [Link]()
print ([Link] ([5, 8, 2]))
O/P: 8
d) [Link] ()
print ([Link] ([5, 8, 2]))
O/P → 2
e) [Link]()
print ([Link] (25))
O/P: 5.0
⑬ Array Indexing
Purpose: accessing individual elements of an array
Ex. a = [Link]([10, 20, 30])
print (a[1])
O/P: 20
⑭ Array Slicing
Purpose: Selecting a part of an array
Ex: a = [Link] ([10, 20, 30, 40, 50])
print (a[1:4])
O/P: [20 30 40]
-Ingle P.