Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Broadcasting in NumP | Master Data Science with Python lesso | BraveProgrammer
  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 9 of 60

·python

Broadcasting in NumPy

20 minutes

Course progress15%

Broadcasting

Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes by implicitly expanding the smaller array.

Simple broadcast example

import numpy as np

A = np.arange(6).reshape(2,3)
B = np.array([10, 20, ])   
C = A + B   
(C)
30
# shape (3,)
# B is broadcast across rows
print

Rules of broadcasting

  1. Align dimensions from the right.
  2. If dimensions are equal, they are compatible.
  3. If one dimension is 1, the array behaves as if it were copied.
  4. Otherwise, broadcasting fails.

Higher‑dimensional broadcast

A = np.ones((2,1,3))
B = np.arange(3)   # shape (3,)
C = A * B   # result shape (2,1,3)
print(C.shape)

When broadcasting fails

np.arange(4) + np.arange(3)   # ValueError

Practical tip

Use np.broadcast_to to explicitly broadcast an array:

B = np.arange(3)
B_broadcast = np.broadcast_to(B, (2,3))
print(B_broadcast)

Info

Broadcasting is the secret sauce behind many NumPy‑based algorithms.
Make it stickPractice what you've learned1 quiz · 4 practical tests · Optional activities from Master Data Science with PythonBrowse activities
Previous lessonIndexing, Slicing, and Iterating in NumPyContinue to lesson 10Mathematical Operations with NumPyBack to Master Data Science with Python curriculum