Shape mismatch: objects cannot be broadcast to a single shape

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
5 min

banner

# Table of Contents

  1. Shape mismatch: objects cannot be broadcast to a single shape
  2. Using list slicing to solve the error
  3. How to correctly broadcast arrays in NumPy

# Shape mismatch: objects cannot be broadcast to a single shape

The Python "ValueError: shape mismatch: objects cannot be broadcast to a single shape" occurs when the two inputs you've supplied have incompatible shapes.

To solve the error, make sure that the x and y inputs have the same or compatible shapes.

Here is an example of how the error occurs when using matplotlib.

main.py
import matplotlib.pyplot as plt x = ['bobby', 'hadz'] y = [2, 4, 6] # ⛔️ ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (2,) and arg 1 with shape (3,). plt.bar(x, y) # ⛔️ ValueError: ... plt.barh(x, y) plt.show()

value error shape mismatch objects cannot be broadcast to single shape

Notice that the shapes of the x and y lists are not the same and are not compatible.

The first list has 2 elements and the second has 3.

The matplotlib.pyplot.bar() method makes a bar plot.

The x parameter is used to specify the x coordinates of the bars.

The y parameter is used to specify the height(s) of the bars.

The two parameters are related, therefore the supplied lists (or arrays) have to either be of the same or compatible shapes.

For example, if I make both lists of 3 elements each, everything works as expected.

main.py
import matplotlib.pyplot as plt x = ['bobby', 'hadz', 'com'] y = [2, 4, 6] plt.bar(x, y) plt.show()

make both parameters have compatible shapes

The code for this article is available on GitHub

If you need to check the length of a one-dimensional list, use the len() function.

main.py
x = ['bobby', 'hadz', 'com'] print(len(x)) # 👉️ 3

If you need to get the length of a 2D array, check out the following article.

# Using list slicing to solve the error

If your x and y parameters are not the same (or compatible) shapes, use list slicing.

main.py
import matplotlib.pyplot as plt x = ['bobby', 'hadz'] y = [2, 4, 6] plt.bar(x, y[:len(x)]) plt.show()

use list slicing to solve the error

The code for this article is available on GitHub

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

We used the len() function when specifying the stop index.

The x list only has 2 items, so we used len(x) to specify a stop index of 2 and select only the first 2 elements of the y list.

# How to correctly broadcast arrays in NumPy

Broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations.

The smaller array is "broadcast" across the larger array so that they have compatible shapes.

You will usually do NumPy operations on a pair of arrays, element-wise.

In the simplest case, the two arrays will have the same shape.

main.py
import numpy as np x = np.array([1, 2, 3]) y = np.array([2, 2, 2]) print(x * y) # 👉️ [2 4 6]
The code for this article is available on GitHub

The arrays have 3 elements each, so we multiplied them element-wise without running into any issues.

However, if the two arrays have incompatible shapes, the ValueError is raised.

main.py
import numpy as np x = np.array([1, 2, 3]) y = np.array([2, 2]) # ⛔️ ValueError: operands could not be broadcast together with shapes (3,) (2,) print(x * y)

The first array has 3 elements and the second has only 2.

Their shapes are incompatible, so they cannot be broadcast together.

You can also broadcast an array and a scalar value.

main.py
import numpy as np x = np.array([1, 2, 3]) y = 2 print(x * y) # 👉️ [2 4 6] arr = np.broadcast_arrays(x, y) print(arr) # 👉️ [array([1, 2, 3]), array([2, 2, 2])]
The code for this article is available on GitHub

NumPy knows that we are trying to multiply each element of the x array by y.

This is equivalent to setting y to an array containing 3 elements with a value of 2 - np.array([2, 2, 2]).

You can imagine that NumPy stretches the scalar 2 into an array that contains 3 elements with a value of 2.
main.py
y = 2 # becomes the following array y = np.array([2, 2, 2])

When you do arithmetic operations with a pair of arrays, NumPy compares their shapes element-wise.

It starts with the rightmost dimension and works its way left.

Two dimensions are compatible when:

  1. The dimensions are equal.
  2. One of the dimensions is 1.

If neither of the 2 conditions is met, a ValueError is raised.

You can use the shape attribute if you need to print the shape of an array.

main.py
import numpy as np x = np.array([1, 2, 3]) print(x.shape) # 👉️ (3,) y = np.array([2, 2]) print(y.shape) # 👉️ (2,)
The code for this article is available on GitHub

The numpy.shape attribute returns the shape of an array.

The returned tuple contains the lengths of the array's dimensions.

Note that the arrays don't have to have the same number of dimensions.

main.py
import numpy as np x = np.array([1, 2, 3]) print(x.shape) # 👉️ (3,) y = np.array([[2], [2]]) print(y.shape) # 👉️ (2, 1) # [[2 4 6] # [2 4 6]] print(x * y)

The first array is one-dimensional and the second array is two-dimensional.

The returned array will have the same number of dimensions as the supplied array that has the greatest number of dimensions.

The size of each dimension is the largest size of the corresponding dimension along the provided arrays.

Missing dimensions are assumed to have a size of 1.

As previously noted, arrays with a size of 1 are stretched to match the other array.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.