Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Unit 4 — Reshaping & Element-wise Operations

Lesson 43 of 50 in the free Python Programming notes on Siksha Sarovar, written by Rohit Jangra.

Re-shaping of an Array & Element-wise Operations

Reshaping an Array

reshape() changes an array's dimensions without changing its data — the total number of elements must stay the same.

import numpy as np

a = np.arange(1, 13)         # [1 2 3 4 5 6 7 8 9 10 11 12]
print(a.shape)                  # (12,)

b = a.reshape(3, 4)               # reshape to 3 rows x 4 columns
print(b)
# [[ 1  2  3  4]
#  [ 5  6  7  8]
#  [ 9 10 11 12]]

c = a.reshape(4, 3)
print(c)

d = a.reshape(2, 2, 3)             # 3D array: 2 blocks of 2x3
print(d.shape)                       # (2, 2, 3)

flat = b.flatten()                    # back to 1D
print(flat)                             # [1 2 3 4 5 6 7 8 9 10 11 12]
reshape() fails with a ValueError if the requested shape doesn't match the total element count (e.g. reshaping 12 elements into (3, 5)).

Element-wise Operations

NumPy applies arithmetic operators to every element automatically (no loop needed) — called vectorization.

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

print(a + b)     # [11 22 33 44]
print(a - b)      # [-9 -18 -27 -36]
print(a * b)       # [10 40 90 160]
print(b / a)         # [10. 10. 10. 10.]
print(a ** 2)          # [1 4 9 16]

Operations with a scalar (broadcasting)

a = np.array([1, 2, 3, 4])
print(a + 10)     # [11 12 13 14]
print(a * 2)       # [2 4 6 8]
print(a > 2)         # [False False True True]  -- element-wise boolean comparison

Element-wise math functions

a = np.array([1, 4, 9, 16])
print(np.sqrt(a))     # [1. 2. 3. 4.]
print(np.exp([1, 2]))  # [2.718... 7.389...]
print(np.log(a))         # natural log of each element