w3resource

NumPy: Check whether the dimensions of two given arrays are same or not

NumPy: Array Object Exercise-180 with Solution

Write a NumPy program to check whether the dimensions of two given arrays are same or not.

Pictorial Presentation:

Python NumPy: Check whether the dimensions of two given arrays are same or not

Sample Solution:

Python Code:

import numpy as np
def test_array_dimensions(ar1,ar2):
 try:
   ar1 + ar2
 except ValueError:
   return "Different dimensions"
 else:
   return "Same dimensions"
ar1 = np.arange(20).reshape(4,5)
ar2 = np.arange(20).reshape(4,5)
print(test_array_dimensions(ar1, ar2))
ar1 = np.arange(20).reshape(5,4)
ar2 = np.arange(20).reshape(4,5)
print(test_array_dimensions(ar1, ar2))

Sample Output:

Same dimensions
Different dimensions

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to fetch all items from a given array of 4,5 shape which are either greater than 6 and a multiple of 3.
Next: Write a NumPy program to place a specified element in specified time randomly in a specified 2D array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}