Understanding 2D Arrays in Python
What is a 2D Array?
A 2D array is like a table with rows and columns. It can represent data such as a marksheet, seating chart, or
a matrix.
1. Creating a 2D Array
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
2. Accessing Elements
print(matrix[0][1]) # Output: 20
print(matrix[2][2]) # Output: 90
3. Changing a Value
matrix[1][1] = 55 # Changes 50 to 55
print(matrix)
4. Looping Through a 2D Array
for row in matrix:
for value in row:
print(value, end=' ')
print()
Student Activity
Task:
1. Create a 2D array for 2 students with 3 subject marks.
2. Print total marks for each student.
Understanding 2D Arrays in Python
Sample Code:
marks = [
[85, 90, 80],
[70, 75, 65]
for i in range(len(marks)):
total = sum(marks[i])
print('Student', i + 1, 'Total Marks:', total)
Bonus: Using NumPy (Optional)
import numpy as np
arr = np.array([[1, 2], [3, 4]])
print(arr[1][1]) # Output: 4
code one dimensional array
print("How many element to store in the list ? ", end="")
n = input()
arr = []
print("\nEnter", n, "Elements: ", end="")
n = int(n)
for i in range(n):
element = input()
arr.append(element)
print("\nThe list is:")
for i in range(n):
print(arr[i], end=" ")
code for two dimensional array
# Python 3 program to demonstrate working
# of method 1 and method 2.
rows, cols = (5, 5)
Understanding 2D Arrays in Python
# method 2 1st approach
arr = [[0]*cols]*rows
# lets change the first element of the
# first row to 1 and print the array
arr[0][0] = 1
for row in arr:
print(row)
# method 2 2nd approach
arr = [[0 for i in range(cols)] for j in range(rows)]
# again in this new array lets change
# the first element of the first row
# to 1 and print the array
arr[0][0] = 1
for row in arr:
print(row)
Inserting Values
We can insert new data elements at specific position by using the insert() method and specifying the
index.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
T.insert(2, [0,5,11,13,6])
for r in T:
for c in r:
print(c,end = " ")
print()
Deleting the Values
from array import *
T = [[11, 12, 5, 2], [15, 6,10],
Understanding 2D Arrays in Python
[10, 8, 12, 5], [12,15,8,6]]
del T[3]
for r in T:
for c in r:
print(c,end = " ")
print()