# How to check if a matrix is a square matrix in Numpy?

In this tutorial, we will look at how to check if a numpy matrix (a 2d numpy array) is a square matrix or not with the help of some examples.

### What is a square matrix?

A matrix is said to be a square matrix if the number of rows is equal to the number of columns in the matrix. The following image shows a square matrix and a non-square matrix.

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

You can see that the number of rows and columns in a square matrix is the same, hence the name square.

## How to check if a matrix is a square matrix in Numpy?

To check if a matrix is a square matrix or not, use the `numpy.ndarray.shape` property. For a 2d array, the `.shape` property returns a `(m, n)` tuple where `m` is the number of rows and `n` is the number of columns. To check if the matrix is square or not, simply check if `m` is equal to `n` or not.

The following is the syntax –

```import numpy as np

# check if the matrix ar is square
len(ar.shape) == 2 and ar.shape == ar.shape```

In the above syntax, we’re basically checking if the array is a 2d array with the same number of rows and columns.

Let’s now look at some examples of using the above syntax –

### Example

Let’s create a square matrix and check if the above method identifies it correctly or not.

```import numpy as np

# create a square matrix
ar = np.array([
[1, 2],
[3, 4]
])

# check if the matrix ar is square
print(len(ar.shape) == 2 and ar.shape == ar.shape)```

Output:

`True`

Here, we created a 2×2 square matrix and used the above method. We get `True` as the output indicating the array `ar` is a square matrix.

Let’s look at an example where the matrix is not a square matrix.

```import numpy as np

# create a matrix
ar = np.array([
[1, 2, 3],
[4, 5, 6]
])

# check if the matrix ar is square
print(len(ar.shape) == 2 and ar.shape == ar.shape)```

Output:

`False`

Here, we applied the method on a 2×3 matrix. We get `False` as the output which indicates that the matrix `ar` is not a square matrix.

Note that if you apply this method on a non-2d array, you’ll get `False` as the result.

```import numpy as np

# create a matrix
ar = np.array([1, 2, 3, 4])

# check if the matrix ar is square
print(len(ar.shape) == 2 and ar.shape == ar.shape)```

Output:

`False`

You might also be interested in –

• 