0% found this document useful (0 votes)
4 views31 pages

Unit II Python

This document provides an overview of control statements in Python, including break, continue, and pass statements, as well as their syntax and usage through examples. It also covers conditional statements, loops, and file handling, explaining how to manage the flow of execution in a program. Additionally, it describes the importance of control statements for making decisions, repeating code, and handling errors.

Uploaded by

duttapiyush404
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)
4 views31 pages

Unit II Python

This document provides an overview of control statements in Python, including break, continue, and pass statements, as well as their syntax and usage through examples. It also covers conditional statements, loops, and file handling, explaining how to manage the flow of execution in a program. Additionally, it describes the importance of control statements for making decisions, repeating code, and handling errors.

Uploaded by

duttapiyush404
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
You are on page 1/ 31

1 Unit - II

Unit- II
Control Statements in Python:
What are Control Statements in Python?
Control statements are an essential aspect of any programming language, including Python.
Control statements in Python are used to manage the flow of execution of a program based on
certain conditions.
Control statements in Python are a powerful tool for managing the flow of execution. They allow
developers to make decisions based on specific conditions and modify the normal sequential
flow of a program. By using control statements effectively, developers can write more efficient
and effective code.
Types of Control Statements in Python
There are three types of control statements in Python.

Break Statement in Python


The break statement is used to terminate a loop, i.e., for loop, while loop, or nested loop. When a
break statement executes inside a loop, it immediately terminates the loop and transfers control
to the statement following the loop
Flow Chart of Break Statement in Python

Prof. Shubhra chinchmalatpure


2 Unit - II

Syntax of Break Statement in Python

while condition:

# statements

if condition:

break

# statements after break statement

In this syntax, the break statement is used inside a loop (while loop or for loop). When the
condition specified in the if statement is true, the break statement is executed, and the control is
transferred to the next statement after the loop. This means that the loop is terminated, and the
code execution continues from the statement after the loop.

Example of Break Statement in Python

list_of_numbers = [1, 3, 7, 9, 11, 12, 13, 15]


for num in list_of_numbers:
if num % 2 == 0:
print("The first even number is:", num)
break
Output:
The first even number is: 12

Explanation:
In this example, we have a list called list_of_numbers. We want to find the first even number in
this list. We use a for loop to iterate over the list, and inside the loop, we use an if statement to
check if the current number is even. If the current number is even, we print it as the first even
number, and we use the break statement to exit the loop.

Continue Statement in Python


The continue statement is used to skip a particular iteration of a loop when a specific condition is
met. When a continue statement is executed inside a loop, it skips the current iteration of the
loop and jumps to the next iteration.

Prof. Shubhra chinchmalatpure


3 Unit - II

Flow chart of Continue Statement in Python

Syntax of Continue Statement in Python


while condition:

# statements before the continue statement

if condition:

continue

# statements after the continue statement

In this syntax, when the condition specified in the if statement is true, the continue statement is
executed, and the control is transferred to the next iteration of the loop. This means that the
current iteration is skipped, and the loop continues with the next iteration.
Example of Continue Statement in Python

numbers = [1, 3, 7, 8, 9, 11, 12, 15]


for num in numbers:
if num % 2 == 0:
continue
print(num)

Prof. Shubhra chinchmalatpure


4 Unit - II

Output:
1
3
7
9
11
15
Explanation: We have a list of integers called numbers. Only the odd numbers from this list
should be printed. We use a for loop to traverse through the list, and an if statement inside the
loop checks if the current number is even. If the current number is an even integer, we apply the
continue statement to skip the current iteration and proceed to the next. We print the current
number if it is odd.
Pass Statement in Python
The pass statement is a placeholder statement that does nothing. It is used when a statement is
required syntactically, but you don’t want to execute any code. Pass is mostly used as a
placeholder for functions or conditional statements that have not yet been implemented.

Syntax of Pass Statement in Python

while condition:

# statements before the pass statement

if condition:

pass

# statements after the pass statement

In this syntax, the pass statement is used inside a loop (while loop or for loop) and inside an if
statement. When the pass statement is executed, it does nothing, and the control is transferred to
the next statement after the loop or the if statement.

Prof. Shubhra chinchmalatpure


5 Unit - II

Example of Pass Statement in Python

x = 25

if x > 15:

pass

else:

print("x is less than or equal to 15")

Explanation: In this example, we have a variable called x that has a value of 10. We want to
print a message when the value of x is greater than 5. We use an if statement to check if the value
of x is greater than 5. Inside the if statement, we use the pass statement as a placeholder for the
code that we haven’t written yet. If the value of x is less than or equal to 5, we print a message.

When we run this program, it will not output anything, as the pass statement does nothing.
However, it serves as a placeholder for the code that we will write in the future.

Uses of Control Statements in Python

1. Conditionally executing code: The if-else statement is used to execute specific code
based on a condition. This allows us to selectively execute certain parts of the code based
on the input data or the state of the program.

2. Repeating code: Loops such as for loop and while loop are used to execute a block of
code repeatedly based on a condition. This is useful when we want to perform a specific
operation multiple times, such as processing a list of items or iterating over a range of
numbers.

3. Exiting loops: The break statement is used to exit a loop prematurely when a specific
condition is met. This is useful when we want to terminate a loop when we have found
the desired value or have encountered an error condition.

4. Skipping iterations: The continue statement is used to skip a specific iteration of a loop
when a particular condition is met. This is useful when we want to exclude specific
values from the loop, such as even numbers or duplicates.

5. Handling errors: The try-except statement is used to handle errors that may occur
during the execution of a program. This allows us to gracefully handle errors and prevent
the program from crashing.

Prof. Shubhra chinchmalatpure


6 Unit - II

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.


If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so
we print to screen that "b is greater than a".
Elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this
condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so
we print to screen that "a and b are equal".

Prof. Shubhra chinchmalatpure


7 Unit - II

Else
The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
n this example a is greater than b, so the first condition is not true, also the elif condition is not
true, so we go to the else condition and print to screen that "a is greater than b".

And
The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a = 200

b = 33

c = 500

if a > b and c > a:

print("Both conditions are True")

Prof. Shubhra chinchmalatpure


8 Unit - II

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200

b = 33

c = 500

if a > b or a > c:

print("At least one of the conditions is True")

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:

Example

Test if a is NOT greater than b:

a = 33

b = 200

if not a > b:

print("a is NOT greater than b")

Prof. Shubhra chinchmalatpure


9 Unit - II

Nested If

You can have if statements inside if statements, this is called nested if statements.

Example

x = 41

if x > 10:

print("Above ten,")

if x > 20:

print("and also above 20!")

else:

print("but not above 20.")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content,
put in the pass statement to avoid getting an error.

Example
a = 33
b = 200
if b > a:
pass

Python Loops

Python has two primitive loop commands:

• while loops
• for loops

The while Loop

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

Prof. Shubhra chinchmalatpure


10 Unit - II

Example Get your own Python Server

Print i as long as i is less than 6:

i=1

while i < 6:

print(i)

i += 1

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).

This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example Get your own Python Server

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

The for loop does not require an indexing variable to set beforehand.

Prof. Shubhra chinchmalatpure


11 Unit - II

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":
print(x)
Short-Circuiting Techniques in Python
This “laziness” on the part of the interpreter is called “short-circuiting” and is a common
way of evaluating Boolean expressions in many programming languages. Similarly, for an
and expression, python uses a short circuit technique to speed truth value evaluation.
By short-circuiting, we mean the stoppage of execution of a Boolean operation if the truth value
of the expression has been determined already. The evaluation of expression takes place from
left to right. In Python, short-circuiting is supported by various Boolean operators and functions.

Short-Circuiting in Boolean Operators


The chart given below gives an insight into the short-circuiting case of boolean expressions.
Boolean operators are ordered by ascending priority.

or: When the Python interpreter scans or expression, it takes the first statement and checks to see
if it is true. If the first statement is true, then Python returns that object’s value without checking

Prof. Shubhra chinchmalatpure


12 Unit - II

the second statement. The program does not bother with the second statement. If the first value is
false, only then Python checks the second value, and then the result is based on the second half.
and: For an and expression, Python uses a short circuit technique to check if the first statement is
false then the whole statement must be false, so it returns that value. Only if the first value is
true, does it check the second statement and return the value.
An expression containing and or stops execution when the truth value of expression has been
achieved. Evaluation takes place from left to right.
What is a Text file in Python?
A text file is a computer file that is structured as lines of electronic text. For the purposes of
programming and Python, it is a file containing a single string-type data object. Generally, it is
also encoded by the computer and must be decoded before it can be parsed by a program.
Write String to Text File in Python
Python – Write String to Text File
To write string to a file in Python, we can call write() function on the text file object and pass the
string as argument to this write() function.

In this tutorial, we will learn how to write Python String to a file, with the help of some Python
example programs.

Following is the step by step process to write a string to a text file.

Open the text file in write mode using open() function. The function returns a file object.
Call write() function on the file object, and pass the string to write() function as argument.
Once all the writing is done, close the file using close() function.

Write string to new text file


The following is an example Python program in its simplest form to write string to a
text file.
Python Program
#open text file
text_file = open("D:/data.txt", "w")

#write string to file


text_file.write('Python Tutorial by TutorialKart.')

#close file
text_file.close()
Prof. Shubhra chinchmalatpure
13 Unit - II

Write string value to an existing file

If you try to write a string to an existing file, be careful. When you create a file in write mode
and call write() function, existing data is lost and new data is written to the file.

For instance, in the previous example, we created a file and written some data to it.

Now we shall run the following example.

Python Program
#open text file
text_file = open("D:/data.txt", "w")

#write string to file


n = text_file.write('Hello World!')

#close file
text_file.close()

Python Directory and Files Management

A directory is a collection of files and subdirectories. A directory inside a directory is known as a


subdirectory.

Python has the os module that provides us with many useful methods to work with directories
(and files as well).

Get Current Directory in Python

We can get the present working directory using the getcwd() method of the os module.

This method returns the current working directory in the form of a string. For example,

import os

print(os.getcwd())

# Output: C:\Program Files\PyScripter

Prof. Shubhra chinchmalatpure


14 Unit - II

Here, getcwd() returns the current directory in the form of a string.

Changing Directory in Python

In Python, we can change the current working directory by using the chdir() method.

The new path that we want to change into must be supplied as a string to this method. And
we can use both the forward-slash / or the backward-slash \ to separate the path elements.

example,

import os

# change directory
os.chdir('C:\\Python33')

print(os.getcwd())

Output: C:\Python33

Here, we have used the chdir() method to change the current working directory and passed a new
path as a string to chdir().
File Handling in Python
File handling is an important activity in every web app. The types of activities that you can
perform on the opened file are controlled by Access Modes. These describe how the file will be
used after it has been opened.

These modes also specify where the file handle should be located within the file. Similar to a
pointer, a file handle indicates where data should be read or put into the file.

In Python, there are six methods or access modes, which are:

Read Only ('r’): This mode opens the text files for reading only. The start of the file is where
the handle is located. It raises the I/O error if the file does not exist. This is the default mode for
opening files as well.
Read and Write ('r+’): This method opens the file for both reading and writing. The start of the
file is where the handle is located. If the file does not exist, an I/O error gets raised.

Prof. Shubhra chinchmalatpure


15 Unit - II

Write Only ('w’): This mode opens the file for writing only. The data in existing files are
modified and overwritten. The start of the file is where the handle is located. If the file does not
already exist in the folder, a new one gets created.
Write and Read ('w+’): This mode opens the file for both reading and writing. The text is
overwritten and deleted from an existing file. The start of the file is where the handle is located.
Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet
exist, a new one gets created. The handle is set at the end of the file. The newly written data will
be added at the end, following the previously written data.
Append and Read (‘a+’): Using this method, you can read and write in the file. If the file
doesn't already exist, one gets created. The handle is set at the end of the file. The newly written
text will be added at the end, following the previously written data.
Below is the code required to create, write to, and read text files using the Python file handling
methods or access modes.

How to Create Files in Python


In Python, you use the open() function with one of the following options – "x" or "w" – to create
a new file:
"x" – Create: this command will create a new file if and only if there is no file already in
existence with that name or else it will return an error.
Example of creating a file in Python using the "x" command:
#creating a text file with the command function "x"
f = open("myfile.txt", "x")
We've now created a new empty text file! But if you retry the code above – for example, if you
try to create a new file with the same name as you used above (if you want to reuse the filename
above) you will get an error notifying you that the file already exists. It'll look like the image
below:

Prof. Shubhra chinchmalatpure


16 Unit - II

"w" – Write: this command will create a new text file whether or not there is a file in the memory
with the new specified name. It does not return an error if it finds an existing file with the same
name – instead it will overwrite the existing file.

Example of how to create a file with the "w" command:

#creating a text file with the command function "w"

f = open("myfile.txt", "w")

#This "w" command can also be used create a new file but unlike the the "x" command the "w" c

With the code above, whether the file exists or the file doesn't exist in the memory, you can still
go ahead and use that code. Just keep in mind that it will overwrite the file if it finds an existing
file with the same name.

How to Write to a File in Python

There are two methods of writing to a file in Python, which are:

The write() method:

This function inserts the string into the text file on a single line.

Based on the file we have created above, the below line of code will insert the string into the
created text file, which is "myfile.txt.”

file.write("Hello There\n")

How to Read From a Text File in Python

There are three methods of reading data from a text file in Python. They are:

The read() method:

This function returns the bytes read as a string. If no n is specified, it then reads the entire file.

Prof. Shubhra chinchmalatpure


17 Unit - II

Example:

f = open("myfiles.txt", "r")

#('r’) opens the text files for reading only

print(f.read())

#The "f.read" prints out the data in the text file in the shell when run.

The readline() method:

This function reads a line from a file and returns it as a string. It reads at most n bytes for the
specified n. But even if n is greater than the length of the line, it does not read more than one
line.

f = open("myfiles.txt", "r")

print(f.readline())

Array

What Is an Array?

An array is a data structure that lets us hold multiple values of the same data type. Think of it as
a container that holds a fixed number of the same kind of object. Python makes coding easier for
programmers.

Creating an Array in Python

An array is created by importing an array module to the Python program.

Syntax: from array import *

Prof. Shubhra chinchmalatpure


18 Unit - II

arrayName = array(typecode, [ Initializers ])

Example:

ypecodes are alphabetic representations that are used to define the type of value the
array is going to store. Some common typecodes are:

Typecode Value

Represents signed integer of


b
size 1 byte

Represents unsigned integer of


B
size 1 byte

Prof. Shubhra chinchmalatpure


19 Unit - II

Represents character of size 1


c
byte

Represents signed integer of


i
size 2 bytes

Represents unsigned integer of


I
size 2 bytes

Represents floating-point of size


f
4 bytes

Represents floating-point of size


d
8 bytes

Prof. Shubhra chinchmalatpure


20 Unit - II

Accessing the Elements of an Array


To access an array element, you need to specify the index number. Indexing starts at 0—not at 1.

Hence, the index number is always one less than the length of the array.

Example:

One-Dimensional Array
In computer science, arrays serve as a data structure for the contiguous storage of elements
sharing the same data type. Arrays allow for the consolidation of multiple values of a uniform
data type within a single variable. Various types of arrays facilitate the storage of values in
different configurations, with one-dimensional arrays being one of the most frequently employed
structures for this purpose.
Definition of One-Dimensional Array
One Dimensional Array can be defined as follows.

The most basic type of array is a one dimensional array, in which each element is stored linearly
and may be retrieved individually by providing its index value.
A collection of elements with the same data type that are kept in a linear arrangement under a
single variable name is referred to as a one dimensional array.
One Dimensional Array
The one-dimensional array is considered one of the simplest forms of arrays, known for its ease
of use and definition in programming. This type of array is particularly practical as a data

Prof. Shubhra chinchmalatpure


21 Unit - II

structure because it allows for straightforward initialization and modification of the stored
values.

Declaration Syntax of One Dimensional Array

data_type array_name [array_size];

where,

array_name = name of the one dimensional array

array_size = defines the number of elements in the array

Initialization Syntax of One Dimensional Array

Simply adding a list to the right side of the One Dimensional Array’s declaration syntax
initializes it. Simply said, we assign values to the defined 1D Array according to the supplied
array size.
data_type array_name [array_size] = {comma_separated_element_list};

Note: The defined Array Size shall not be exceeded by the number of entries supplied in the list.

Example of Declaration of One Dimensional Array

int arr [10] ; // Declaring a 1D array of size 10

int roll_no [5] = {1, 2, 3, 4, 5} ; // Initializing a 1D array of size 5

char names[30] = {"Raj, John, Krish"} ; // Initializing a 1D array of ty

Input Elements in a One Dimensional Array

There are just a few techniques available for assigning and storing values in one dimensional
array. Let’s look at the two most popular approaches to better comprehend.

1. Direct Initialization of One Dimensional Array

The elements are allocated in this procedure at the time the 1D Array is declared.

Example

int num [10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};

Prof. Shubhra chinchmalatpure


22 Unit - II

2.User Input Method of One-Dimensional Array

With this approach, the user is prompted to enter an array of items during program execution.
Example of Input Elements in One Dimensional Array:

• C++
#include <iostream>
using namespace std;
int main()
{
int num [5];
cout<<"Enter array elements: \n";
for(int i = 0; i < 5 ; i++)
{
cin >> num[i] ;
}
}

Output

Enter array elements:

Accessing Elements of One Dimensional Array

To find out what the elements of a 1D Array are, we may either display the full array or use the
indexing technique to display only the values of the array that we need.
Note: Indexing an array always begins at 0.

Example of Accessing Elements of One Dimensional Array

// To print a single element of an array

Prof. Shubhra chinchmalatpure


23 Unit - II

int arr [5] = {1, 3, 5, 7, 9};

cout << arr[3]; // arr[3] i.e. index 3 of the array will print the value

Python Lists as One-Dimensional Arrays:


One-dimensional array contains elements only in one dimension. In other words, the shape of the
NumPy array should contain only one value in the tuple. We can create a 1-D array in NumPy
using the array() function, which converts a Python list or iterable object.
import numpy as np
# Create a one-dimensional array from a list
array_1d = np.array([1, 2, 3, 4, 5])
print(array_1d)
Output
[1 2 3 4 5]
A Python list is an ordered, mutable sequence of elements. It can hold elements of different data
types.
Lists are dynamic, meaning their size can change during runtime.
Example of creating and using a list:
# Creating a one-dimensional list
my_list = [10, 20, 30, 40, 50]

# Accessing elements by index (0-based)


print(f"First element: {my_list[0]}")
print(f"Third element: {my_list[2]}")

# Modifying an element
my_list[1] = 25
print(f"Modified list: {my_list}")

# Adding elements

Prof. Shubhra chinchmalatpure


24 Unit - II

my_list.append(60) # Adds to the end


my_list.insert(0, 5) # Inserts at a specific index
print(f"List after adding elements: {my_list}")

# Removing elements
my_list.remove(30) # Removes the first occurrence of the value
popped_element = my_list.pop(2) # Removes and returns element at index
print(f"List after removing elements: {my_list}")
print(f"Popped element: {popped_element}")

# Iterating through a list


print("Elements in the list:")
for element in my_list:
print(element)
NumPy Arrays for Numerical Operations:
For numerical computations, especially with large datasets, the NumPy library provides ndarray
objects, which are more efficient than Python lists for array-like operations.
NumPy arrays are homogeneous, meaning all elements must be of the same data type.
Example of creating and using a NumPy array:
import numpy as np

# Creating a one-dimensional NumPy array


numpy_array = np.array([1, 2, 3, 4, 5])

# Accessing elements
print(f"NumPy array: {numpy_array}")
print(f"Element at index 3: {numpy_array[3]}")

# Performing vectorized operations (element-wise)


Prof. Shubhra chinchmalatpure
25 Unit - II

squared_array = numpy_array * numpy_array


print(f"Squared array: {squared_array}")

# Slicing
sliced_array = numpy_array[1:4]
print(f"Sliced array: {sliced_array}")
Using Fromiter()
Fromiter() is useful for creating non-numeric sequence type array however it can create any type
of array. Here we will convert a string into a NumPy array of characters.
import numpy as np
# creating the string
str = "geeksforgeeks"
# creating 1-d array
x = np.fromiter(str, dtype='U2')
print(x)
Output:
['g' 'e' 'e' 'k' 's' 'f' 'o' 'r' 'g' 'e' 'e' 'k' 's']
2D Array in Python
A 2D array in python is a two-dimensional data structure used for storing data generally in a
tabular format. For example, if you want to store a matrix and do some computations, how would
you do it in Python? Well, the answer is the use of 2D arrays in Python.
In Python, a two-dimensional array is commonly represented using nested lists, where an outer
list contains multiple inner lists, and each inner list represents a row in the array.
Example using nested lists:
# Creating a 3x3 two-dimensional array (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

Prof. Shubhra chinchmalatpure


26 Unit - II

# Accessing elements
print(f"Element at row 0, column 1: {matrix[0][1]}") # Output: 2
print(f"Element at row 2, column 0: {matrix[2][0]}") # Output: 7
# Modifying an element
matrix[1][2] = 10
print(f"Modified matrix: {matrix}") # Output: [[1, 2, 3], [4, 5, 10], [7, 8, 9]]
# Iterating through the array
print("Iterating through the matrix:")
for row in matrix:
for element in row:
print(element, end=" ")
print()
What is 2D Array in Python & Its Uses
A 2D array in python is a two-dimensional data structure stored linearly in the memory. It means
that it has two dimensions, the rows, and the columns, and thus it also represents a matrix. By
linear data structure, we mean that the elements are linearly placed in memory, and each element
is connected to its previous and next elements.
We visualize a 2D array in a tabular format, but actually, elements are stored linearly in memory.
Elements of a 2D array are contiguously placed in the memory. It means that if one element is
present at the current memory address, the next element will be placed at the next memory
address. This type of storage makes arrays randomly accessible. It means that we can access any
element of the array independently.

Prof. Shubhra chinchmalatpure


27 Unit - II

In a 2D array, multiple arrays are inserted as elements in an outer array. Each element in a 2D
array is represented by two indices, the row and the column. 2D arrays in python are zero-
indexed, which means counting indices start from zero rather than one; thus, zero is the first
index in an array in python.

2D arrays are used wherever a matrix needs to be represented. We can create a 2D array with n
rows and m columns representing an mxn matrix.

2D arrays are also used to store data in a tabular format. 2D arrays are also used to represent a
grid while working with graphics, as the screen is also represented as a grid of pixels.

Syntax of Python 2D Array


We can create a 2D array in python as below:

Prof. Shubhra chinchmalatpure


28 Unit - II

array_name=[n_rows][n_columns]

Where array_name is the array's name, n_rows is the number of rows in the array, and
n_columns is the number of columns in the array.

This syntax only creates the array, which means that memory space is reserved for this array, but
we will add the values later.

There is another syntax for creating a 2D array where initialization (creation of array and
addition of elements) is done with a single line of code. This syntax is as follows:

array_name=[[r1c1,r1c2,r1c3,..],[r2c1,r2c2,r2c3,...],. . . .]
Where array_name is the array's name, r1c1, r1c1 etc., are elements of the array. Here r1c1
means that it is the element of the first column of the first row. A 2D array is an array of arrays.
Accessing Values in Python 2D Array
We can directly access values or elements of a 2D array in Python. It can be done by using the
row and column indices of the element to be accessed. It has the following syntax:
array_name[row_ind][col_ind]
Where array_name is the array's name, row_ind is the row index of the element, and col_ind is
the column index of the element.
If we specify only one index while accessing an array, this index is treated as the row index, and
the whole row is returned. It has the syntax:
array_name[row_ind]
Where array_name is the array's name, row_ind is the row index to be accessed.
If an index exceeds the size, if the array is provided to this function, it returns the index out of
range error. Such indices are known as out of bounds. It is further clarified by the examples
below.

Prof. Shubhra chinchmalatpure


29 Unit - II

Accessing Single Element


In this example, we first initialize an array named arr with the given values, then access a single
element of the arr array present at the 3rd column in the second row. As arrays are 0-indexed, we
will use the values 1 and 2.

arr=[[1,2,3],[4,5,6],[7,8,9]]

print("Element at [1][0]=",arr[1][0])

Output:
Element at [1][0]= 4
Accessing an Internal Array
In this example, we only pass the row index, i.e., 2, to access the 2D array arr. At that location,
another array is present, and thus that array is returned to us.

Code:
arr=[[1,2,3],[4,5,6],[7,8,9]]

Prof. Shubhra chinchmalatpure


30 Unit - II

print("Element at [2]=",arr[2])
Output:
Element at [2]= [7, 8, 9]
traversing Values in Python 2D Array

Traversing means sequentially accessing each value of a structure. Traversing in a 2D array in


python can be done by using a for a loop. We can iterate through the outer array first, and then at
each element of the outer array, we have another array, our internal array containing the
elements. So for each inner array, we run a loop to traverse its elements.

As you can see in the above image, the arrows are marked in sequence. The first row is traversed
horizontally, then we come down to the second row, traverse it, and finally come down to the last
row, traversed.
In this example, we traverse the array named arr by using two for loops. The first for loop
iterates the outer array, returning the internal arrays and the second for loop traverses each of the
inner loops, returning the elements.

Code:
arr=[[1,2,3],[4,5,6],[7,8,9]]

for _ in arr:
for i in _:
print(i,end=" ")
print()

Prof. Shubhra chinchmalatpure


31 Unit - II

Output:
123
456
789
Inserting Values in Python 2D Array

nserting a value in an array means adding a new element at a given index in the array and then
shifting the remaining elements accordingly. Inserting a value would cause the values after to be
shifted forward.
Example using NumPy (for numerical operations and efficiency):
For more advanced numerical operations or when dealing with large datasets, the NumPy library
is highly recommended as it provides efficient array objects.
import numpy as np
# Creating a 2D array using NumPy
numpy_array = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
# Accessing elements
print(f"Element at row 0, column 1 (NumPy): {numpy_array[0, 1]}") # Output: 2
# Performing array operations (e.g., adding a scalar)
numpy_array_plus_one = numpy_array + 1
print(f"NumPy array after adding 1: {numpy_array_plus_one}")

Prof. Shubhra chinchmalatpure

You might also like