Shape mismatch: objects cannot be broadcast to a single shape

Borislav Hadzhiev

Last updated: Jul 6, 2023

Reading time·4 min

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

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()`

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()`

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.

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()`

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.

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 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])]`

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:

- The dimensions are equal.
- 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 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.

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

- ValueError: all the input array dimensions for the concatenation axis must match exactly
- ValueError: cannot reshape array of size X into shape Y
- lbfgs failed to converge (status=1): STOP: TOTAL NO. of ITERATIONS REACHED LIMIT
- How to draw empty circles on a Scatter Plot in Matplotlib
- TypeError: Image data cannot be converted to float [Solved]
- OverflowError: Python int too large to convert to C long
- How to use numpy.argsort in Descending order in Python
- Object arrays cannot be loaded when allow_pickle=False
- ufunc 'add' did not contain loop with signature matching types
- AttributeError: Can only use .dt accessor with datetimelike values
- Get the column names of a NumPy ndarray in Python
- Finding the Range of NumPy Array elements in Python
- Usecols do not match columns, columns expected but not found