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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Master Data Science with Python

Lesson 9 of 60 · python

Broadcasting in NumPy

Duration: 20 minutes

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, 30])   # shape (3,)
C = A + B   # B is broadcast across rows
print(C)

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.

Previous: Indexing, Slicing, and Iterating in NumPyNext: Mathematical Operations with NumPy