0% found this document useful (0 votes)
3 views57 pages

Unit-2-Introduction To Python Programming

The document provides an introduction to Python programming, covering key concepts such as programming languages, translators, compilers, and interpreters. It explains the basic structure of a Python program, including comments, variable declarations, and data types, as well as the importance of indentation and the use of keywords. Additionally, it discusses input and output functions, type conversion, and operators in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views57 pages

Unit-2-Introduction To Python Programming

The document provides an introduction to Python programming, covering key concepts such as programming languages, translators, compilers, and interpreters. It explains the basic structure of a Python program, including comments, variable declarations, and data types, as well as the importance of indentation and the use of keywords. Additionally, it discusses input and output functions, type conversion, and operators in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-2

Introduction
to
Python Programming
Program and Programming Language
An ordered set of instructions or commands executed by a computer is called program. The language used to
write these instructions is called programming language. For example, C, C++, Java, Python etc. Python is a
programming language created by GUido Van Rossum in 1991.

Translator
Translator is a software that converts the high level language program to machine language.

e
nc
Compiler and Interpreter

ie
Sc
Compiler:
A compiler converts the high level language program in machine language.

p.
om
1. Compiler translates the whole program at once.
2. Errors are shown after compilation.
3. Execution is faster.
rC
4. Example: C, C++
re

Interpreter:
tu

Interpreter also converts the high level language program in machine language but line by line.
ec

1. Prgram is translated line by line.


|L

2. Errors are shown when it occurs in any line.


3. Execution is slower.
ar

4. Example: Python, Java Script


hw

To write and run a Python program, we need to have a Python interpreter installed on our computer. The
es

interpreter is also called Python shell. The symbol >>> is called Python prompt which indicates that the
interpreter is ready to retrieve instructions.
ah
M

Execution Modes
There are two ways to run a program using python interpreter: a) Intractive mode b) Script mode
(A) Intractive mode
In this mode, we type a python statement on the >>> prompt. As soon as we press enter, the interpreter
executes the statement and display the result.

e
Disadvantage: We cannot save the statements for future use and we have to

nc
retype the statement to run them again.

ie
(B) Script mode

Sc
In this mode, we write a Python program in a file, save it and then use the interpreter to execute the program

p.
from the file.

om
Python IDLE(Integrated Development and Learning Environment) can be used to create program.
rC
re
tu
ec
|L
ar
hw

To execute the program,


es

1. Open the program using an editor, for eaxmple IDLE.


2. In IDLE, go to Run ->Run Module to execute the program.
ah
M

3. The output appears on the shell.


Basic Structure of a Python Program

e
nc
1. Comments (optional)

ie
2. Import statements (optional)

Sc
3. Variable declarations
4. Function definitions (optional)
5. Main program code

p.
om
Example of Python Program Structure rC
In [2]: # This is a comment

import math # Importing a module
re


tu

a = 10 # Variable
b = 20
ec


def add(x, y): # Function definition
|L

return x + y

result = add(a, b) # Main code
ar

print("Sum =", result)


hw

Sum = 30
es

Important Rules in Python Structure


ah

✔ Indentation (spaces) is very important


M

✔ No need for ; (semicolon)


✔ Code runs line by line (top to bottom)
✔ Case-sensitive (A ≠ a)
Python Keywords
Keywords are the reserve words. Each keyword has a specific meaning to teh python Interpreter.

For example:
and, or, break, continue, if, else, import, True, for, while

Identifiers

e
nc
Identifiers are the names to identify a variable, function or other entities in a program.

ie
The rules for naming an identifier in Python are as follows:

Sc
1. The name should begin with an uppercase or a lowercase alphabet or an undersco
re sign(_).

p.
2. It can be of any length.

om
3. It should not be a keyword or reserved word.
4. Special symbols like @, #, $, % etc. cannot be used.
rC
Identifier cannot start with a digit.
re
tu
ec
|L
ar
hw
es
ah
M

variables
Variables are identifiers whose value can change. For example,

In [3]: age=50
print("age: ",age)
age=70
print("age: ",age)

age: 50
age: 70
Variable names are case-sensitive.

a=4

A = "Sally"

Variables must always assigned values before using in prgram, otherwise it will lead to an error.

In [5]: marks
print("marks: ",marks)

---------------------------------------------------------------------------

e
NameError Traceback (most recent call last)

nc
<ipython-input-5-3a4e4b69dd54> in <module>()
----> 1 marks

ie
2 print("marks: ",marks)

Sc
NameError: name 'marks' is not defined

p.
om
Data Types rC
Data types identifies the type of data which a variable can hold.
re
tu
ec
|L
ar
hw
es
ah

Mutable and Immutable Data Types


M

Mutable Data Types


Mutable types are those whose value can be changed in place. Only three types are mutable in Pyhton.

1. Lists
2. Dictionaries
3. Sets
Immutable types
Immutable types are those that can never change their value in place. The following are the immutable
dayatypes:

1. integer
2. floating point numbers
3. Boolean

e
nc
ie
Sc
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
Operators in Python
An operator is used to perform specific mathematical or logical operation on values. The values that the
operator works on are called operands. For example,

In [1]: a=10
b=20
c=a+b #here, a and b are operands and + is an arithmetic operator.
print("c: ",c)

c: 30

e
nc
Types of operators ¶

ie
Sc
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M

Examples
In [9]: p=51
q=4
r=p//q #arithmetic operator
print("r: ",r)

r: 12
In [5]: a=20 #Assignment operator
b=20
c=a==b #relational operator
print("c: ",c)

c: True

In [10]: a=10
b=20
c=30
result=a<b<=c
print("Result: ", result )

Result: True

e
nc
In [6]: a=10
b=0

ie
c= a and b #logical operator

Sc
print("c: ",c)

c: 0

p.
In [7]: L=[10,20,30,40]

om
c= 20 in L #membership operator
print("c: ",c)
rC
c: True
re

Operator precedence and Associativity


tu
ec
|L
ar
hw
es
ah
M
Expression Evaluation
In [12]: result=5+(6/2)**2+10*5
print("Result: ",result)

Result: 64.0

In [22]: a=2+-+-3
while a>2:
print(a)
break

e
nc
5

ie
In [23]: result= 4**2/4*(5+9)

Sc
print("Result: ",result)

Result: 56.0

p.
In [24]: result=16%4**3//5+8

om
print("Result: ",result)

Result: 11
rC
In [26]: a=50-10*3
re

b=(50-10)*3
print("Rule A: ", a)
tu

print("Rule B: ", b)
ec

Rule A: 20
Rule B: 120
|L

In [27]: result=(2-6+3**2*3)+7
ar

print("Result: ",result)
hw

Result: 30
es

In [28]: result=12.0/4+(9+1.0)
print("Result: ",result)
ah

Result: 13.0
M

In [12]: x,z=5,10
y=x+3
x=x-1
x=x+z
print('x:',x,'y:',y,'z:',z)

x: 14 y: 8 z: 10
In [15]: print(type(1+3))
print(type(1+3.0))

<class 'int'>
<class 'float'>

In [17]: print(type(11+3))
print(type('11'+3))

<class 'int'>

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-c048cfe30a0e> in <module>()

e
1 print(type(11+3))

nc
----> 2 print(type('11'+3))

ie
TypeError: must be str, not int

Sc
Associativity of Operators in Python

p.
om
In Python, associativity determines the order in which operators with the same precedence are evaluated
when they appear in an expression.
rC
1. If two operators have the same precedence, the expression is evaluated from le
re

ft to right.
tu

2. Most operators in Python have left-to-right associativity.


ec

3. The exponentiation (**), assignment (=, +=, etc.), logical NOT (not) operators
|L

have right-to-left associativity.


ar

In [18]: a=5-4-3
hw

b=3**2**3
print(a)
es

print(b)

-2
ah

6561
M

In [22]: x,y=4,8
z=x/y*y
print(z)

4.0
In [19]: a,b,c=1,1,2
d=a+b
e=1.0
f=1.0
g=2.0
h=e+f
print(c==d)
print(c is d)
print(g==h)
print(g is h)

True
True
True

e
False

nc
ie
Sc
p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
Python Comments
1. Comments can be used to explain Python code.

2. Comments can be used to make the code more readable.

3. Comments can be used to prevent execution when testing code.

e
Creating a Comment

nc
Comments starts with a ' # ', and Python will ignore them:

ie
Sc
In [1]: #This is a comment

print("Hello, World!")

p.
Hello, World!

om
A comment does not have to be text that explains the code, it can also be used to prevent Python from
rC
executing code:
re

In [2]: #print("Hello, World!")


print("Cheers, Mate!")
tu

Cheers, Mate!
ec
|L

You can add a multiline string (triple quotes(''' ''')) in your code, and place your comment inside it:
ar

In [3]: """
This is a comment
hw

written in
more than just one line
"""
es

print("Hello, World!")
ah

Hello, World!
M

Input and Output statements in python


In Python, user input is handled by the input() function, and output is displayed using the print() function. Both
are built-in functions, not statements.

Input in Python
The input() function is used to get data from the user via the keyboard.
Syntax:
variable = input("prompt_message")

Default Type:
The input() function always returns the user's input as a string by default, regardless of what is typed.

Type Conversion:
To work with other data types (like integers or floats), you must explicitly convert the input using typecasting
functions like int() or float().

e
In [8]: # Basic string input

nc
name = input("Enter your name: ")
print("Hello,", name) # Output: Hello, [user's name]

ie

# Integer input (with type conversion)

Sc
age_str = input("Enter your age: ")
age_int = int(age_str)
print("Next year you will be", age_int + 1)

p.
Enter your name: Maheshwar

om
Hello, Maheshwar
Enter your age: 36
rC
Next year you will be 37
re

Output in Python
tu

The print() function displays output to the console.


ec
|L

Syntax:
print(value(s), sep='separator', end='end_character', ...)
ar
hw

Multiple Arguments:
es

You can print multiple items by separating them with commas(,).


ah

sep Parameter:
M

The optional sep argument allows you to specify a custom separator (e.g., sep='-' or sep='* ').

end Parameter:
The optional end argument defines what to print at the end of the line. By default, it's a newline character
('\n'), which moves the cursor to the next line. Changing it (e.g., end=' ' or end='') keeps subsequent prints on
the same line.
In [22]: # Basic output
print("Hello, World!")

# Printing multiple items with default space separator
print("My", "name", "is", "James") # Output: My name is James

# Using a custom separator
print("My", "name", "is", "James", sep="**") # Output: My**name**is**James
#

# Using the 'end' parameter to keep output on the same line
print("Today is Monday,", end=" ")
print("I like string beans.") # Output: Today is Monday, I like string beans.

e
Hello, World!

nc
My name is James
My**name**is**James

ie
Today is Monday, I like string beans.

Sc
Type Conversion in Python

p.
Type conversion in Python is the process of changing a value's data type from one to another.

om
This can happen automatically (implicit conversion) or manually by the programmer (explicit conversion, also
rC
known as type casting).
re

Implicit Type Conversion


tu

Implicit conversion occurs automatically when the Python interpreter safely converts a "lower" data type to a
ec

"higher" one.
|L

Example: Adding an integer and a float results in a float.


ar

In [10]: num_int = 10 # int


num_float = 3.5 # float
hw

result = num_int + num_float


print(result) # Output: 13.5
print(type(result)) # Output: <class 'float'>
es

13.5
ah

<class 'float'>
M

Explicit Type Conversion (Type Casting)


Explicit conversion is performed by the programmer using built-in functions to convert data to a specific
required type.

This is necessary when Python cannot perform implicit conversion (e.g., adding an integer and a string).
In [13]: a = 100 # int
b = "200" # string

# This would cause a TypeError: print(a + b)

# Explicitly convert the string to an integer to perform addition
result = a + int(b)
print(result) # Output: 300

300

Debugging in python

e
nc
The process of finding and fixing errors (bugs) in code is called debugging.

ie
Errors in Python code

Sc
Due to errors, a program may not execute or may generate wrong output. Python errors can be broadly
categorized into three main types:

p.
1. Syntax Errors

om
2. Logical Errors
3. Runtime Errors
rC
1. Syntax Errors
re

These errors occur when the Python interpreter finds a mistake in the structure or grammar of the code,
tu

preventing the program from running at all. Common examples include: Missing colons at the end of
ec

statements
|L

In [14]: if True
print('Here')
ar

File "<ipython-input-14-d35ceb8ad0c1>", line 1


hw

if True
^
SyntaxError: invalid syntax
es
ah

Mismatched parentheses or quotation marks


M

In [17]: print(Welcome to IP Lab)

File "<ipython-input-17-4b0ecfc28bf3>", line 1


print(Welcome to IP Lab)
^
SyntaxError: invalid syntax

Incorrect or inconsistent indentation, which Python uses to define code block


In [16]: if True:
print('Here')

File "<ipython-input-16-0e583e4e2ded>", line 2


print('Here')
^
IndentationError: expected an indented block

2. Logical Errors/ Semantic Errors


A logical error does not stop execution but the program behaves incorrectly and produces undesired/wrong

e
output. It is difficult to identify these errors because program interprets successfully.

nc
Examples include:

ie
Sc
Using an incorrect mathematical formula for a calculation.

To find the average of two numbers 10 and 12, if we write the code 10 + 12/2, it would run successfully and

p.
produce the result 16.0, which is wrong. The correct code to find the average is (10 + 12)/2 and the output will

om
be 11.0
rC
In [20]: average= 10 + 12/2
print("Average: ", average)

re

average= (10 + 12)/2


print("Average: ", average)
tu

Average: 16.0
ec

Average: 11.0
|L

3. Runtime Errors
ar

A runtime error causes abnormal termination of program while it is executing. A runtime errors is when the
hw

statement is correct syntactically, but the interpreter can not execute it.
es

For example,
ah

ZeroDivisionError: Occurs when a number is divided by zero.


M
In [21]: a=10
b=0
c=a/b
print("c: ", c)

---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-21-de5770b9f362> in <module>()
1 a=10
2 b=0
----> 3 c=a/b
4 print("c: ", c)

ZeroDivisionError: division by zero

e
nc
In [23]: name=shyam

ie
print(name)

Sc
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-3c17deb64c97> in <module>()

p.
----> 1 name=shyam

om
2 print(name)

NameError: name 'shyam' is not defined


rC
re

In [24]: add="seven"+3
print(add)
tu

---------------------------------------------------------------------------
ec

TypeError Traceback (most recent call last)


<ipython-input-24-915ecc38acba> in <module>()
|L

----> 1 add="seven"+3
2 print(add)
ar

TypeError: must be str, not int


hw
es
ah
M
Types of statements in Python
Statements are the instructions given to the computer to perform any task. python statements
belong to the following categories:

1. Empty Statement(Null Statement)


2. Simple statement
3. Compound statement

1. Empty Statement

ce
A statement which does nothing is called empty statement or Null statement. In python, an
empty statement is pass statement.

en
ci
Syntax

S
pass

p.
In [4]: for i in range(1,11):
if (i==5): om
rC
pass
else:
print(i, end=" ")
re


tu

1 2 3 4 6 7 8 9 10
ec

2. Simple Statement
|L

Any single executable statement is called a simple statement in Python. For example,
ar
hw

In [7]: name =input("Enter your name: ") #simple statement


print("Hello! ",name) #simple statement
es

Enter your name: Maheshwar


Hello! Maheshwar
ah
M

Compound Statement
A group of statements executed as a unit are called compound statements. Compound
statement has a header line and a body:

Header line
It begins with a keyword and ends with a colon(:)

Body
Body consists of one or more Python statements each indented inside the header line.
In [11]: num=int(input("Enter the number: "))
if num>0: #header line
print("Great!") #Body
print("Your entered positive number.")
elif num<0: #header line
print("Oh!") #Body
print("Your entered negative number.")
else: #header line
print("Hmm!") #Body
print("Your entered 0.")

Enter the number: 24


Great!
Your entered positive number.

ce
if and for statements are example of control statements.

en
ci
Control Statements

S
p.
In a program, statements are executed sequentially, selectively and iteratively. Every
programming language provides constructs to support sequence, selection and iteration.

Sequence
om
rC

In this, statements are executed sequentially. This is the default flow of the program.
re
tu
ec
|L
ar
hw
es
ah
M

Selection
Selection means the execution of statements depends on a condition test. if condition
evaluates to True, then statements following the condition are executed. Otherwise, a different
set of statements are executed. For this, if-else, if-elif-else are used.
ce
en
S ci
Iteration

p.
om
Iteration means repetition of set of statements depending upon a condition test. Till the
condition is true, set of statements are repeated. As soon as the condition becomes false, the
repetition stops. For loop and while loop are used for iteration in Python.
rC
re
tu
ec
|L
ar
hw
es
ah
M
if-else statements
Usually, statements are executed one after another in a program. However, there are sitution
when we have more than one option to choose from based on certain condition. This is done
using if-else conditional or selection statements. There are three ways to write if-else
statements:

1. if statement
It executes the statements inside if, when the condition is true.

ce
In [1]: age=int(input("Enter your age: "))
if age>=18:

en
print("You can cast your vote.")

Enter your age: 24

ci
You can cast your vote.

S
p.
2. if-else statement
om
It executes the statements inside if when the condition is true otherwise executes the
statements inside else.
rC

In [2]: age=int(input("Enter your age: "))


re

if age>=18:
print("You can cast your vote.")
tu

else:
ec

print("You can not cast your vote.")

Enter your age: 16


|L

You can not cast your vote.


ar

3. if-elif-else statement
hw

It checks multiple conditions and executes statements accordingly. Meaning of elif is elseif.
es

In [3]: num=int(input("Enter the number: "))


ah

if num>0:
print("Your entered positive number.")
M

elif num<0:
print("Your entered negative number.")
else:
print("Your entered 0.")

Enter the number: -100


Your entered negative number.

for loop
The for keyword is used to create a for loop.
In [5]: for x in range(1, 9):
print(x, end=" ")

1 2 3 4 5 6 7 8

In [8]: fruits = ["apple", "banana", "cherry"]



for x in fruits:
print(x, end=" ")

apple banana cherry

The while Loop

ce
With the while loop we can execute a set of statements as long as a condition is true.

en
ci
In [9]: i = 1
while i < 6:

S
print(i, end=" ")
i += 1

p.
1 2 3 4 5
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
List
List is a mutable datatype in python that can store a sequence of values of any type. e.g. L=
[1,2,3,4,5] Here, L is a list of integers.

L2 = [1,2,3,'a','b', "abc"], Here list is of mixed datatypes.

In [3]: L = [1,2,3,4,5]
print("List is: ", L)

List is: [1, 2, 3, 4, 5]

ce
In [2]: L = [1,2,3,'a','b', "abc"]

en
print("Mixed Datatype list: ", L)

Mixed Datatype list: [1, 2, 3, 'a', 'b', 'abc']

S ci
KeyPoints about List

p.
om
1. List is a mutable datatype i.e. modifiable. The elements of list can be modified.
2. List elements can be of any type.
rC
3. Values of elements in list can be changed inplace.
4. List can be empty i.e. without any element and is written as L= []
re

In [39]: L= [1,2,3,4,5]
tu

L[2]= 10
ec

print(" Updated list is: ", L) #Values of elements in list can be changed in

Updated list is: [1, 2, 10, 4, 5]


|L
ar

Nested List
hw

List can have another list as an element e.g. L= [1,2,[3,4],5,6]. Here, List element at index 2 is
a list itself. So, elements are accessed as L[2][0] giving element 3 and L[2][1] giving element
es

4.
ah

In [8]: L= [1,2,[3,4],5,6]
M

print("Element of inner nested list are: ", L[2][0],"and", L[2][1])

Element of inner nested list are: 3 and 4

Creating List
To create a list, put a number of elements in the square bracket separated with commas. e.g.
In [ ]: L= [] # Empty List
L= [1,2,3,4] # List of integers
L= ['a','b','c'] # List of characters
L= ["abc","def","ghi"] # List of string

Empty List
Empty list can be created using two ways.

1. L= []
2. L= list()

ce
Traversing a List

en
Traversing a list means accessing and processing each element of the list. Each element of

ci
the list can be accessed or traverse using a for loop or while loop.

S
p.
(A) List traversal using for loop:
In [3]: L=[1,5,10,15,20, 25,30]
for item in L:
om
rC
print(item, end=" ")

1 5 10 15 20 25 30
re
tu

Another way include using range() and len() functions


ec

In [9]: L=[1,5,10,15,20, 25,30]


|L

for i in range(len(L)):
print(L[i],end=" ")
ar

1 5 10 15 20 25 30
hw

(B) List traversal using while loop:


es
ah

In [10]: L=[1,5,10,15,20, 25,30]


i=0
while i <len(L):
M

print(L[i], end=" ")


i=i+1

1 5 10 15 20 25 30

List Manipulation
In Python, list manipulation means modifying a list after it has been created. This is done
using various built-in methods, operators, and functions.

In Python, a function is a standalone block of code, while a method is a function that is


associated with an object or class.

All methods are functions, but not all functions are methods.

Built-in Functions for Lists


These functions take a list as an argument and generally return a new value, rather than
dif i th li t i l

ce
en
S ci
p.
om
rC
re
tu

len()
ec

In [8]: L=[100,5,20,15,40, 15,10]


|L

length=len(L)
print("\nLength of the List is: ",length)
ar

Length of the List is: 7


hw
es

max()
ah

In [7]: L=[100,5,20,15,40, 15,10]


M

maximum=max(L)
print("\nMaximum element in the List is: ",maximum)

Maximum element in the List is: 100


min()
In [5]: L=[100,5,20,15,40, 15,10]
minimum=min(L)
print("\nMinimum element in the List is: ",minimum)

Minimum element in the List is: 5

sum()

ce
In [4]: L=[100,5,20,15,40, 15,10]
total=sum(L)

en
print("\nSum of all elements in the list is: ",total)

ci
Sum of all elements in the list is: 205

S
p.
sorted()
In [3]: L=[100,5,20,15,40, 15,10] om
rC
L1=sorted(L)
print("\nThe sorted list is:", L1)
re

The sorted list is: [5, 10, 15, 15, 20, 40, 100]
tu
ec

list()
|L

In [2]: string="Maheshwar"
L2=list(string)
ar

print("\nThe list formed from given string is: ",L2)


hw

The list formed from given string is: ['M', 'a', 'h', 'e', 's', 'h', 'w',
es

'a', 'r']
ah

List Methods
M

List methods are functions called on a specific list object using the dot syntax (e.g.,
my_list.append(item)).
These methods often modify the list in-place.
ce
en
S ci
p.
om
rC
re
tu

append()
ec
|L

In [23]: L=[100,5,20,15,40, 15,10]


[Link](75)
print("List after append is: ",L)
ar

List after append is: [100, 5, 20, 15, 40, 15, 10, 75]
hw

extend()
es
ah

In [28]: L=[100,5,20,15,40, 15,10]


L3=[100,200,300,400,500]
M

[Link](L3)
print("Extended list L is: ", L)

Extended list L is: [100, 5, 20, 15, 40, 15, 10, 100, 200, 300, 400, 500]

Difference between append() and extend() methods

The main difference is that append() adds a single element to a list, even if that element is
another list, while extend() adds multiple elements from an iterable (like a list, tuple, or string)
to the list individually. For example,
In [3]: L=[100,5,20,15,40, 15,10]
L1=[2,4,8]
[Link](L1)
print("List after append is: ", L)
L=[100,5,20,15,40, 15,10]
[Link](L1)
print("\nList after extend is: ", L)

List after append is: [100, 5, 20, 15, 40, 15, 10, [2, 4, 8]]

List after extend is: [100, 5, 20, 15, 40, 15, 10, 2, 4, 8]

clear()

ce
In [24]: L=[100,5,20,15,40, 15,10]

en
[Link]()
print("\nlist after clear() method is: ",L)

S ci
list after clear() method is: []

p.
copy()
om
rC
In [26]: L=[100,5,20,15,40, 15,10]
L1=[Link]()
print("\nCopied list L1 is: ",L1)
re
tu

Copied list L1 is: [100, 5, 20, 15, 40, 15, 10]


ec
|L

count()
ar

In [27]: L=[100,5,20,15,40, 15,10]


item=int(input("\nEnter the element you want to count: "))
hw

print("\nThe item", item, "is present",[Link](item)," in the list.")


es

Enter the element you want to count: 15


ah

The item 15 is present 2 in the list.


M

index()
In [29]: L=[100,5,20,15,40, 15,10]
index=[Link](15)
print("The first occurance of the item is: ", index)

The first occurance of the item is: 3


insert(i,x)
In [31]: L=[100,5,20,15,40, 15,10]
item=int(input("Enter the item to be inserted: "))
position=int(input("\nEnter the position where to insert: "))
[Link](position, item)
print("\nThe list after insertion is: ",L)

Enter the item to be inserted: 50

Enter the position where to insert: 4

The list after insertion is: [100, 5, 20, 15, 50, 40, 15, 10]

ce
en
pop()

ci
In [1]: L=[100,5,20,15,40, 15,10]

S
[Link]()
print("The list after pop() is called: ",L)

p.
i=int(input("Enter the position: "))

om
[Link](i) #pop() item from a specific position
print("The list after pop() is called: ",L)

The list after pop() is called: [100, 5, 20, 15, 40, 15]
rC
Enter the position: 3
The list after pop() is called: [100, 5, 20, 40, 15]
re
tu

remove()
ec

In [2]: L=[100,5,20,15,40, 15,10]


|L

[Link](15)
print("The list after removal is: ",L)
ar

The list after removal is: [100, 5, 20, 40, 15, 10]
hw

Difference between pop() and remove() methods


es
ah

In Python, the primary difference that the remove() method deletes an element by its value,
while the pop() method deletes an element by its index.
M

Additionally, pop() returns the removed element, whereas remove() does not return anything.
In [1]: L=[100,5,20,15,40, 15,10]
i=int(input("Enter the index of the element: "))
item=[Link](i)
print("\nThe deleted element is: ", item)
print("\nThe list after deletion is: ", L)

L=[100,5,20,15,40, 15,10]
ele=int(input("\nEnter the element to be deleted: "))
item=[Link](ele)
print("\nThe deleted element is: ", item)
print("\nThe list after deletion is: ", L)

Enter the index of the element: 3

The deleted element is: 15

ce
The list after deletion is: [100, 5, 20, 40, 15, 10]

en
Enter the element to be deleted: 15

ci
The deleted element is: None

S
p.
The list after deletion is: [100, 5, 20, 40, 15, 10]

reverse() om
rC
In [38]: L=[1,2,3,4,5, 6, 7]
L1=[Link]() #reverse does not return anything. So, Value in L1 is
re

print("The reverse of List is: ", L)


tu

print("\nThe L1 is: ", L1)


ec

The reverse of List is: [7, 6, 5, 4, 3, 2, 1]


|L

The L1 is: None


ar

sort()
hw

In [36]: L=[100,5,20,15,40, 15,10]


es

L1=[Link]() #sort does not return anything. So, Value in L1 is No


print("The sort List is: ", L)
ah

print("\nThe L1 is: ", L1)

The sort List is: [5, 10, 15, 15, 20, 40, 100]
M

The L1 is: None


List Operations
The most commom operations that can be perform with lists include joining lists, replicating
lists and slicing lists.

1. Joining Lists
Concatenation operator + is used to perform joining operation on the lists.

In [1]: List1=[1,3,5]
List2=[6,7,8]
print(List1+List2)

ce
[1, 3, 5, 6, 7, 8]

en
ci
Important: The + operator when used with lists requres that both the operands must be
list types. A number or any other value can not be added to a list.

S
p.
In [2]: list1=[10,12,14]
list2=list1+2
print(list2)
om
---------------------------------------------------------------------------
rC
TypeError Traceback (most recent call last)
<ipython-input-2-2203921e9c87> in <module>()
re

1 list1=[10,12,14]
----> 2 list2=list1+2
tu

3 print(list2)
ec

TypeError: can only concatenate list (not "int") to list


|L

In [37]: list1=[10,12,14]
ar

list2=list1+"abc"
print(list2)
hw

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
es

<ipython-input-37-7960175ff911> in <module>()
1 list1=[10,12,14]
ah

----> 2 list2=list1+"abc"
3 print(list2)
M

TypeError: can only concatenate list (not "str") to list


Note: When += is used with lists then it requires the operand on the
right side to be an iterable and it will dd each element of the iterable
to the list.

In [8]: list1=[10,12,14]
list1+=2 # 2 is not iterable
print(list1)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-31ef8ab44591> in <module>()
1 list1=[10,12,14]
----> 2 list1+=2 # 2 is not iterable

ce
3 print(list1)

en
TypeError: 'int' object is not iterable

ci
In [9]: list1=[10,12,14]

S
list1+="abc" # "abc" is iterable
print(list1)

p.
[10, 12, 14, 'a', 'b', 'c']
om
rC
2. Repeating or Replicating Lists
re

* Operator is used to replicate a list by specified number of times.


tu

In [10]: list1=[2,4,6]
ec

list1=list1*3
print(list1)
|L

[2, 4, 6, 2, 4, 6, 2, 4, 6]
ar

3. Slicing the Lists


hw

L[start:stop] creates a list slice out of the list L with elements falling between indexes start
es

and stop, not including stop.


ah

In [14]: list1=[10,12,14,16,18,20,22,24,30,32,34]
M

seq=list1[3:-3]
print(seq)

[16, 18, 20, 22, 24]

In normal indexing, if the resulting index is outside the list, Python raises an IndexError
Exception. In Python,simply the elements that fall between specified boundaries are returned
without raising any error.
In [17]: list1=[10,12,14,16,18,20,22,24,30,32,34]
print(list1[3:30]) #upper limit is beyond the size of the list.
print(list1[-15:7]) #lower limit is much lower.
print(list1[15:20]) #both limits are out of bound
print(list1[-15:-20]) #both limits are out of bound

[16, 18, 20, 22, 24, 30, 32, 34]


[10, 12, 14, 16, 18, 20, 22]
[]
[]

Lists also support slice steps.

L[start:stop:step]

ce
en
In [20]: list1=[10,12,14,16,18,20,22,24,30,32,34]
print(list1[0:8:2]) #include every 2nd element.
print(list1[::3]) #no start and stop given i.e. from entire list. pick

ci
print(list1[::-1]) #it will reverse list.

S
[10, 14, 18, 22]

p.
[10, 16, 22, 32]
[34, 32, 30, 24, 22, 20, 18, 16, 14, 12, 10]

om
Some Examples
rC
re

In [12]: str1="informatics practices"


print(str1[:3],"and",str1[3:])
tu

print(str1[:-3],"and",str1[-3:])
print(str1[:6],"and",str1[12:])
ec

inf and ormatics practices


|L

informatics practi and ces


inform and practices
ar

In [11]: str2="computer science"


hw

print(str2[:])
print(str2[::2])
print(str2[:4:2])
es

computer science
ah

cmue cec
cm
M

In [13]: L1=["Python","SQL",98,96,34]
print(L1[2:6])
print(L1[0:0])
print(L1[3:-1])

[98, 96, 34]


[]
[96]

Making True Copy of a List


if we write

list1=[1,2,3]
list2=list1
This will not make list2 as a duplicate list of list1.

It will make list2 to point to where list1 is pointing to. So any change made to list1 will
be reflected in list2 as shown in the example.

In [25]: list1=[1,2,3]
list2=list1 #this will not create a copy of list1.
print("list1: ",list1)
print("\nlist2: ",list2)

ce
list1[1]=5
print("\nlist1: ",list1)

en
print("\nlist2: ",list2)

list1: [1, 2, 3]

S ci
list2: [1, 2, 3]

p.
list1: [1, 5, 3]

list2: [1, 5, 3]
om
rC
To make a copy of list1, there are two options:
re

1. Using list() function


2. Using copy() method
tu
ec

Using list() function


|L

In [26]: list1=[1,2,3]
ar

list2=list(list1)
print("\nlist1: ",list1)
hw

print("\nlist2: ",list2)
list1[1]=5
es

print("\nlist1: ",list1)
print("\nlist2: ",list2)
ah

list1: [1, 2, 3]
M

list2: [1, 2, 3]

list1: [1, 5, 3]

list2: [1, 2, 3]

It is now clear that any change made in the list1 are not reflected to list2.
Using copy() method

In [27]: list1=[1,2,3]
list2=[Link]()
print("\nlist1: ",list1)
print("\nlist2: ",list2)
list1[1]=5
print("\nlist1: ",list1)
print("\nlist2: ",list2)

list1: [1, 2, 3]

ce
list2: [1, 2, 3]

list1: [1, 5, 3]

en
list2: [1, 2, 3]

ci
S
Using list slice

p.
In [29]: list1=[1,2,3]
list2=list1[:]
print("\nlist1: ",list1)
om
rC
print("\nlist2: ",list2)
list2[1]=5
re

print("\nlist1: ",list1)
print("\nlist2: ",list2)
tu
ec

list1: [1, 2, 3]
|L

list2: [1, 2, 3]

list1: [1, 2, 3]
ar

list2: [1, 5, 3]
hw
es
ah
M
Dictionary
In Pytho, Dictionary is a mappig between set of keys and a set of values.
A key-value pair is called an item. A key is separated from its value by a colon(:) and items are
separated by commas(,).
Items in dictionaries are unordered i.e. we may not get back the data in the same order in
which we had entered the data initially in the dictionary.

ce
en
S ci
p.
om
rC
Example
re

In [1]: D={1:95,2:99,3:67,4:78,5:50}
print("The dictionary is: ",D)
tu

print("\nItems in the dictionary are: ",[Link]())


ec

print("\nKeys in the dictionary are: ",[Link]())


print("\nValues in the dictionary are: ",[Link]())
|L

The dictionary is: {1: 95, 2: 99, 3: 67, 4: 78, 5: 50}


ar

Items in the dictionary are: dict_items([(1, 95), (2, 99), (3, 67), (4, 78),
(5, 50)])
hw

Keys in the dictionary are: dict_keys([1, 2, 3, 4, 5])


es

Values in the dictionary are: dict_values([95, 99, 67, 78, 50])


ah

Characteristics of a Dictionary
M

1. A dictionary is an unordered set of key: value pairs.


2. Keys of a dictionary must be unique.
3. Dictionary is mutable datatype itself.
4. Dictionary is internally stored as mapping.

Creating a Ditionary
To create a dictionary, the key:value pair are included in curly({}) braces.
Syntax
dictionary_name={key1:value1,key2:value2...}

In [2]: dict1={} #empty dictionary with no element


dict2={1:"Banana",2:"Mango",3:"Apple"}
print("Dictionary 1 is: ", dict1)
print("Dictioanry 2 is: ", dict2)

Dictionary 1 is: {}
Dictioanry 2 is: {1: 'Banana', 2: 'Mango', 3: 'Apple'}

Creating Dictionary using dict() function

ce
In [12]: dict1=dict()

en
dict1[1]="Banana"
dict1[2]="Mango"

ci
print("Dictionary 1 is: ", dict1)

S
Dictionary 1 is: {1: 'Banana', 2: 'Mango'}

p.
In [13]: dict2=dict(1='Apple',2='Grapes',3='Papaya')
print("Dictionary 2 is: ", dict2)

File "<ipython-input-13-801e3b36db2f>", line 1


om
rC
dict2=dict(1='Apple',2='Grapes',3='Papaya')
^
SyntaxError: keyword can't be an expression
re
tu
ec

Why error comes here?


|L

This is because dict() function takes keys as an argument and values of the keys as arguments
values. Means the keys must be valid identifier. As, a variable name cannot start with a number.
ar

So, error comes.


hw

To solve this issue, we can pass list of tuples as shown below:


es

In [14]: dict2=dict([(1,"Apple"),(2,"Grapes"),(3,"Papaya")])
print("The dictionary 2 is: ",dict2)
ah

The dictionary 2 is: {1: 'Apple', 2: 'Grapes', 3: 'Papaya'}


M

Important: The keys of a dictionary must be immutable types e.g. a


Python string, a number, a tuple.

If we give mutable type as key, Python will give error as: "unhashable type". For example,
In [3]: dict1={[1,2]:"apple",[3,4]:"Mango"}
print("The dictionary is: ",dict1)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-671b1d6a5c22> in <module>()
----> 1 dict1={[1,2]:"apple",[3,4]:"Mango"}
2 print("The dictionary is: ",dict1)

TypeError: unhashable type: 'list'

Traversing a dictionary

ce
Each item of a dictionary can be accessed or traversed using for loop. For example,

en
In [1]: #Method 1

ci

S
dict2={1:"Banana",2:"Mango",3:"Apple"}
for key in dict2:

p.
print(key,':',dict2[key],end="|| ")

1 : Banana|| 2 : Mango|| 3 : Apple||

In [2]: # Method 2
om
rC

dict2={1:"Banana",2:"Mango",3:"Apple"}
re

for key, value in [Link]():


print(key,":",value,end="||")
tu

1 : Banana||2 : Mango||3 : Apple||


ec
|L

Built-in Functions for Dictionary


ar
hw
es
ah
M
dict()
In [7]: D=dict([('Mango',500),('banana',100),('Apple',200)])
print("The dictionary is: ",D)

The dictionary is: {'Mango': 500, 'banana': 100, 'Apple': 200}

len()
In [8]: D={1:'Car',23:'Bike',3:'Truck',24:'Planes',15:'Bus'}
length=len(D)

ce
print("\nThe length of the dictionary is: ",length)

en
The length of the dictionary is: 5

S ci
sorted()

p.
In [10]: D={1:'Car',23:'Bike',3:'Truck',24:'Planes',15:'Bus'}
sorted_dictionary=sorted(D)
om
print("\nThe sorted list of dictionary keys is: ",sorted_dictionary )
rC

The sorted list of dictionary keys is: [1, 3, 15, 23, 24]
re
tu

Built-in Methods for Dictionary


ec
|L
ar
hw
es
ah
M
ce
en
S ci
p.
om
rC
re

clear()
tu
ec

In [11]: car = {
"brand": "Ford",
|L

"model": "Mustang",
"year": 1964
}
ar


hw

[Link]()
print(car)
es

{}
ah

copy()
M

In [12]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()
print("The dictionary x is: ",x)

The dictionary x is: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}


get()
In [13]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]("model")
print(x)

Mustang

ce
items()

en
ci
In [14]: car = {
"brand": "Ford",

S
"model": "Mustang",
"year": 1964

p.
}

om

x = [Link]()
print(x)
rC
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])
re

keys()
tu
ec

In [15]: car = {
"brand": "Ford",
|L

"model": "Mustang",
"year": 1964
ar

}

hw

x = [Link]()
print(x)
es

dict_keys(['brand', 'model', 'year'])


ah

pop()
M

In [17]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
removed_value=[Link]("model")
print(car)
print("The removed value is: ",removed_value)

{'brand': 'Ford', 'year': 1964}


The removed value is: Mustang
popitem()
In [19]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

removed_item=[Link]()
print(car)
print("The removed item is: ",removed_item)

{'brand': 'Ford', 'model': 'Mustang'}

ce
The removed item is: ('year', 1964)

en
update()

S ci
In [20]: car = {
"brand": "Ford",

p.
"model": "Mustang",

om
"year": 1964
}

rC
[Link]({"color": "White"})
print(car)

re

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}


tu
ec

values()
|L

In [21]: car = {
ar

"brand": "Ford",
"model": "Mustang",
hw

"year": 1964
}

es

x = [Link]()
print(x)
ah

dict_values(['Ford', 'Mustang', 1964])


M
del()
In [30]: car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

del car["model"]
print(car)

{'brand': 'Ford', 'year': 1964}

ce
Difference between pop() and del

en
ci
The main difference is that the dictionary pop() method returns the value of the removed item,
while the del statement does not return any value.

S
pop()

p.
The pop() method is used when you need to remove a key-value pair and simultaneously use
the value that was associated with the key.
del
om
It simply deletes the item. The value is not accessible after the operation.
rC
re

Write a program to count the number of times a number


appears in a given list.
tu
ec

In [31]: list1=[1,2,3,5,1,3,7,8,9,4,2,6,2,7,4,1,6,8,6,4,1,8,9,8,9,3,5,6,7,2,4,7,5,1,4,5
dict1={}
|L

for i in list1:
if i in dict1:
ar

dict1[i]+=1
else:
hw

dict1[i]=1
for i in dict1:
print(i, "appears ", dict1[i])
es

1 appears 5
ah

2 appears 4
3 appears 3
M

5 appears 4
7 appears 4
8 appears 4
9 appears 3
4 appears 5
6 appears 4
11 appears 1
Nested dictionary
In [16]: info={1:{'name': 'Mahesh','Post': 'PGT', 'School': 'GBSSS J J Colony Bawana'},
2:{'name': 'Ankit', 'Post': 'TGT', 'School':'GBSSS J J Colony Bawana' }
}
for i in info:
print("Employee ", i,":")
print("Name: ", info[i]['name'] )
print("Post: ", info[i]['Post'])
print("School: ", info[i]['School'])
print("\n")

Employee 1 :

ce
Name: Mahesh
Post: PGT

en
School: GBSSS J J Colony Bawana

ci
Employee 2 :

S
Name: Ankit
Post: TGT

p.
School: GBSSS J J Colony Bawana

om
rC

Write a program to exchange the key-value pairs i.e.


keys becomes values and values becomes keys.
re
tu

In [10]: dict1={'a':1,'e':2,'i':3,'o':4,'u':5}
ec

dict2={}
for i in dict1:
|L

dict2[dict1[i]]=i
print(dict1)
print(dict2)
ar

{'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5}


hw

{1: 'a', 2: 'e', 3: 'i', 4: 'o', 5: 'u'}


es
ah
M
Introduction to NumPy
NumPy stands for 'Numerical Python'. It is a package for data analysis and scientific computing with Python.
NumPy uses a multidimensional array object and has functions and tools for working with these arrays.

Installing NumPy
NumPy can be installed by typing following command:

Pip install NumPy

ce
Array

en
ci
An array is a datatype used to store multiple elements where each element is of same type.

S
Important characteristics of array

p.
1. Each element of array is of same datatype.
om
2. The entire array is stored contiguously in memory. This makes operations on array fast.
rC
3. Each element of the array is identified or referred using the name of the array along with the index of the
element.
re
tu

Difference between List and Array


ec
|L
ar
hw
es
ah
M

Creation of NumPy Arrays from List

To create an array and to use its methods, first import NumPy library. The NumPy's array function converts a given
list into an array. For example,
In [3]: import numpy as np
arr1=[Link]([11,-12,33])
print(arr1)

[ 11 -12 33]

Creating a 2-D Array

2-D arrays are created by passing nested lists to the array() function.

In [4]: import numpy as py


arr1=[Link]([[1,2,3],[4,5,6]])
print(arr1)

[[1 2 3]

ce
[4 5 6]]

en
Rank of an array

S ci
The number of axes of an array is called rank of that array. 2-D array has two axes(i.e axis=0 and axis=1). So, 2-D
array has rank [Link] 1-D array has one axis(i.e. axis=0). So, 1-D array has rank 1.

p.
Attributes of NumPy Array om
rC
1. [Link]
re

In [5]: import numpy as py


arr1=[Link]([[1,2,3],[4,5,6]])
tu

print([Link])
ec

2
|L

2. [Link]
ar

It gives the size of array for each dimension.


hw

In [6]: import numpy as py


arr1=[Link]([[1,2,3],[4,5,6]])
print([Link])
es

(2, 3)
ah

3. [Link]
M

It gives the total number of elements of the array.

In [7]: import numpy as py


arr1=[Link]([[1,2,3],[4,5,6]])
print([Link])

4. [Link]
It is the data type of the elements of the array.
In [8]: import numpy as py
arr1=[Link]([[1,2,3],[4,5,6]])
print([Link])

int32

5. [Link]
It specifies the size in bytes of each element of the array.

In [9]: import numpy as py


arr1=[Link]([[1,2,3],[4,5,6]])
print([Link])

ce
Other Ways of Creating NumPy Arrays

en
ci
1. Using array function with specified data type

S
In [10]: import numpy as py

p.
arr1=[Link]([[1,2,3],[4,5,6]], dtype=float)
print(arr1)

[[ 1.
[ 4.
2.
5.
3.]
6.]]
om
rC

2. Using function zero()


re

In [16]: import numpy as py


tu

arr1=[Link]((2,2))
ec

print(arr1)

[[ 0. 0.]
|L

[ 0. 0.]]
ar

Default data type of array created using zero() function is float. This can be changed using dtype
attribute.
hw

In [17]: import numpy as py


arr1=[Link]((2,2), dtype=int)
es

print(arr1)

[[0 0]
ah

[0 0]]
M

3. Using function ones()

In [18]: import numpy as py


arr1=[Link]((2,2))
print(arr1)

[[ 1. 1.]
[ 1. 1.]]

Default data type of array created using ones() function is float. This can be changed using dtype
attribute.
In [19]: import numpy as py
arr1=[Link]((2,2), dtype=int)
print(arr1)

[[1 1]
[1 1]]

4. Using function arange()


Array can be created with numbers in a given range or sequence using arange() function.

In [20]: import numpy as py


arr1=[Link](10)
print(arr1)

[0 1 2 3 4 5 6 7 8 9]

ce
In [5]: import numpy as py

en
arr1=[Link](-2,24,3)
print(arr1)

ci
[-2 1 4 7 10 13 16 19 22]

S
p.
Indexing and Slicing

Indexing
om
rC
The indexing of 1-D array is simple. An array containan ordered collection of data elements where each element is
re

referenced by its index. Index starts from zero e.g. first element has index 0, second element has index 1 and so
on.
tu

In [8]: import numpy as py


ec

arr1=[Link]([2,6,8,19,20,40,30])
print(arr1)
|L

print(arr1[3])
print(arr1[0])
ar

[ 2 6 8 19 20 40 30]
19
2
hw

For 2-D arrays, indexing for both dimensions starts from 0 and each element is referenced through two indexes i
es

and j where i represents the row number and j represents the column number.
ah

In [12]: import numpy as py


arr1=[Link]([[1,2,3],[4,5,6]])
M

print(arr1)
print(arr1[1,2])
print(arr1[1,1])

[[1 2 3]
[4 5 6]]
6
5

Slicing

Using slicing, a part of array can be extracted. To define which part of the array is to be sliced, the start and end
index values can be specified with the array name.
In [17]: import numpy as py
arr1=[Link]([2,6,8,19,20,40,30])
print("Complete array:", arr1)
print("Sliced array:", arr1[2:6])

Complete array: [ 2 6 8 19 20 40 30]


Sliced array: [ 8 19 20 40]

In [24]: import numpy as py


arr1=[Link]([[2,3,4],[5,6,7],[8,9,1]])
print("Complete array:\n", arr1)
print("\nSliced array:\n", arr1[0:2,0:2])

Complete array:
[[2 3 4]
[5 6 7]
[8 9 1]]

ce
Sliced array:
[[2 3]

en
[5 6]]

ci
Operations on Array

S
p.
Arithmetic Opeartions
In [3]: import numpy as np
om
rC
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
re

print("\narr2:\n ",arr2)
print("\narr1 + arr2:\n ",arr1+arr2)
tu

arr1:
ec

[[3 6]
[4 2]]
|L

arr2:
[[10 20]
[15 12]]
ar

arr1 + arr2:
hw

[[13 26]
[19 14]]
es

In [5]: import numpy as np


arr1=[Link]([[3,6],[4,2]])
ah

arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr2:\n ",arr2)
M

print("\narr2 - arr1:\n ",arr2-arr1)

arr1:
[[3 6]
[4 2]]

arr2:
[[10 20]
[15 12]]

arr1 - arr2:
[[ 7 14]
[11 10]]
In [6]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr2:\n ",arr2)
print("\narr2 * arr1:\n ",arr2*arr1)

arr1:
[[3 6]
[4 2]]

arr2:
[[10 20]
[15 12]]

arr1 * arr2:
[[ 30 120]

ce
[ 60 24]]

en
In [7]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])

ci
print("arr1:\n ",arr1)

S
print("\narr2:\n ",arr2)
print("\narr2 / arr1:\n ",arr2/arr1)

p.
arr1:
[[3 6]
[4 2]]

arr2:
om
rC
[[10 20]
[15 12]]
re

arr1 / arr2:
[[ 3.33333333 3.33333333]
tu

[ 3.75 6. ]]
ec

In [9]: import numpy as np


arr1=[Link]([[3,6],[4,2]])
|L

arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr1 power 3:\n ",arr1)
ar

arr1:
[[3 6]
hw

[4 2]]

arr1 power 3:
es

[[3 6]
[4 2]]
ah
M
In [10]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
arr2=[Link]([[10,20],[15,12]])
print("arr1:\n ",arr1)
print("\narr2:\n ",arr2)
print("\narr2%arr1:\n ",arr2%arr1)

arr1:
[[3 6]
[4 2]]

arr2:
[[10 20]
[15 12]]

arr2%arr1:
[[1 2]

ce
[3 0]]

en
Transpose

ci
Transposing an array turns its rows into columns and columns into rows.

S
p.
In [15]: import numpy as np
arr1=[Link]([[3,6],[4,2]])
print("The arrar arr1 is:\n ", arr1)
print("The transpose of arr1 is:\n ",[Link]())

The arrar arr1 is:


om
rC
[[3 6]
[4 2]]
The transpose of arr1 is:
re

[[3 4]
[6 2]]
tu
ec

Sorting
|L

Sorting is to arrange the elements of an array in hierarchical order either in ascending or


descending. By default, numpy does sorting in ascending order.
ar

In 2-D array, sorting can be done along either of the axes i.e. row-wise or column-wise. By
hw

default, srting is done row-wise(i.e. on axis=1).


es

In [16]: import numpy as np


arr1=[Link]([[13,6],[4,2]])
print("The arrar arr1 is:\n ", arr1)
ah

[Link]()
print("The sorted arr1 is:\n ",arr1)
M

The arrar arr1 is:


[[13 6]
[ 4 2]]
The sorted arr1 is:
[[ 6 13]
[ 2 4]]

When axis=0 sorting is done column-wise, which means each column is sorted in ascending
order.
In [17]: import numpy as np
arr1=[Link]([[13,6],[4,2]])
print("The arrar arr1 is:\n ", arr1)
[Link](axis=0)
print("The sorted arr1 is:\n ",arr1)

The arrar arr1 is:


[[13 6]
[ 4 2]]
The sorted arr1 is:
[[ 4 2]
[13 6]]

Concatenating Arrays

ce
Concatenation means joining two or more arrays. [Link]() function is used for this purpose.
Concatenating 1-D array means appending the sequences one after the another.

en
In [4]: import numpy as np

ci
arr1=[Link]([1,2,3,4,5])
arr2=[Link]([6,7,8,9,10])

S
[Link]((arr1,arr2))

p.
Out[4]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

om
**For 2-D arrays, all the dimensions of the arrays to be concatenated must match exactly
except for the dimension or axis along which they need to be joined.**
rC
In [17]: import numpy as np
arr1=[Link]([[1,0],[0,1]])
arr2=[Link]([[10,10],[10,10]])
re

[Link]((arr1,arr2))

tu

Out[17]: array([[ 1, 0],


ec

[ 0, 1],
[10, 10],
|L

[10, 10]])

By default, concatenation happens along axis=0. To do column-wise, axis is set to 1 i.e axis=1
ar

In [18]: import numpy as np


hw

arr1=[Link]([[1,0],[0,1]])
arr2=[Link]([[10,10],[10,10]])
[Link]((arr1,arr2),axis=1)
es

Out[18]: array([[ 1, 0, 10, 10],


ah

[ 0, 1, 10, 10]])
M

In [19]: import numpy as np


arr1=[Link]([[1,0],[0,1]])
arr2=[Link]([[10,10,10],[10,10,10]])
[Link]((arr1,arr2))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-9b62c3f1431a> in <module>()
2 arr1=[Link]([[1,0],[0,1]])
3 arr2=[Link]([[10,10,10],[10,10,10]])
----> 4 [Link]((arr1,arr2))

ValueError: all the input array dimensions except for the concatenation axis must match exa
ctly
Reshaping Arrays

The shape of an array can be modified using the reshape() function.


Reshaping an array cannot be used to change the total number of elements in the array. Attempting to
change the number of elements in the array using reshape() results in an error.

In [22]: import numpy as np


arr1=[Link](10,22)
print("Original array arr1 is: ", arr1)
arr2=[Link](3,4)
print("\nThe modified array is: \n", arr2)
arr3=[Link](2,6)
print("\nThe modified array is: \n", arr3)

ce
Original array arr1 is: [10 11 12 13 14 15 16 17 18 19 20 21]

The modified array is:

en
[[10 11 12 13]
[14 15 16 17]
[18 19 20 21]]

S ci
The modified array is:
[[10 11 12 13 14 15]

p.
[16 17 18 19 20 21]]

Statistical Operation on Arrays om


rC
1. max() function
re

In [24]: import numpy as np


tu

arr1=[Link]([13,78,23,56,83,67,20,19,79])
print("The array arr1 is: ", arr1)
ec

print("\nThe maximum element in array is: ", [Link]())

The array arr1 is: [13 78 23 56 83 67 20 19 79]


|L

The maximum element in array is: 83


ar

In [35]: import numpy as np


arr1=[Link]([[30,10,56,78,45],[60,34,98,56,23]])
hw

print("The array arr1 is: \n", arr1)


print("\nThe row-wise maximum element in array is: ", [Link](axis=1))
print("\nThe column-wise maximum element in array is: ", [Link](axis=0))
es

The array arr1 is:


ah

[[30 10 56 78 45]
[60 34 98 56 23]]
M

The column-wise maximum element in array is: [78 98]

The row-wise maximum element in array is: [60 34 98 78 45]

2. min() function

In [29]: import numpy as np


arr1=[Link]([13,78,23,56,83,67,20,19,79])
print("The array arr1 is: ", arr1)
print("\nThe minimum element in array is: ", [Link]())

The array arr1 is: [13 78 23 56 83 67 20 19 79]

The minimum element in array is: 13


In [34]: import numpy as np
arr1=[Link]([[30,10,56,78,45],[60,34,98,56,23]])
print("The array arr1 is: \n", arr1)
print("\nThe row-wise minimum element in array is: ", [Link](axis=1))
print("\nThe column-wise minimum element in array is: ", [Link](axis=0))

The array arr1 is:


[[30 10 56 78 45]
[60 34 98 56 23]]

The column-wise minimum element in array is: [10 23]

The row-wise minimum element in array is: [30 10 56 56 23]

3. sum() function

ce
In [31]: import numpy as np
arr1=[Link]([13,78,23,56,83,67,20,19,79])

en
print("The array arr1 is: ", arr1)
print("\nThe sum of all elements in the array is: ", [Link]())

ci
The array arr1 is: [13 78 23 56 83 67 20 19 79]

S
The sum of all elements in the array is: 438

p.
In [36]: import numpy as np
arr1=[Link]([[30,10,56,78,45],[60,34,98,56,23]])
print("The array arr1 is: \n", arr1)
om
print("\nThe row-wise sum of elements in array is: ", [Link](axis=1))
rC
print("\nThe column-wise sum of elements in array is: ", [Link](axis=0))

The array arr1 is:


[[30 10 56 78 45]
re

[60 34 98 56 23]]
tu

The row-wise sum of elements in array is: [219 271]


ec

The column-wise sum of elements in array is: [ 90 44 154 134 68]


|L

4. mean() function
ar

In [39]: import numpy as np


hw

arr1=[Link]([13,78,23,56,83,67,20,19,79])
print("The array arr1 is: ", arr1)
print("\nThe mean of all elements in the array is: ", [Link]())
es

The array arr1 is: [13 78 23 56 83 67 20 19 79]


ah

The mean of all elements in the array is: 48.6666666667


M

In [40]: import numpy as np


arr1=[Link]([[30,10,56,78,45],[60,34,98,56,23]])
print("The array arr1 is: \n", arr1)
print("\nThe row-wise mean of elements in array is: ", [Link](axis=1))
print("\nThe column-wise mean of elements in array is: ", [Link](axis=0))

The array arr1 is:


[[30 10 56 78 45]
[60 34 98 56 23]]

The row-wise mean of elements in array is: [ 43.8 54.2]

The column-wise mean of elements in array is: [ 45. 22. 77. 67. 34.]
5. std() function

In [41]: import numpy as np


arr1=[Link]([13,78,23,56,83,67,20,19,79])
print("The array arr1 is: ", arr1)
print("\nThe sum of all elements in the array is: ", [Link]())

The array arr1 is: [13 78 23 56 83 67 20 19 79]

The sum of all elements in the array is: 27.8527876123

In [42]: import numpy as np


arr1=[Link]([[30,10,56,78,45],[60,34,98,56,23]])
print("The array arr1 is: \n", arr1)
print("\nThe row-wise standard deviation of elements in array is: ", [Link](axis=1))

ce
print("\nThe column-wise standard deviation of elements in array is: ", [Link](axis=0))

The array arr1 is:

en
[[30 10 56 78 45]
[60 34 98 56 23]]

ci
The row-wise standard deviation of elements in array is: [ 23.03388808 25.83331183]

S
The column-wise standard deviation of elements in array is: [ 15. 12. 21. 11. 11.]

p.
om
rC
re
tu
ec
|L
ar
hw
es
ah
M
REFERENCES

1. National Council of Educational Research and Training (NCERT). (2023).


Informatics Practices – Class XI. New Delhi: NCERT.
2. Arora, Sumita (2023). Informatics Practices for Class XI. New Delhi:
Dhanpat Rai Publications.
3. W3Schools. Python Tutorial. Retrieved March 2026, from
[Link]

ce
4. Google. Gemini (AI tool). Retrieved from [Link]

en
5. Google. Google Photos (Images used). Retrieved from

ci
[Link]

S
6. Project Jupyter. (n.d.). Jupyter Notebook (Software). Retrieved from

p.
[Link]

om
rC
re
tu
ec
|L
ar
hw
es
ah
M

You might also like