In this tutorial, we will look at how to get the number of columns of a 2D array in Numpy with the help of some examples.

## How to get the number of columns in Numpy?

You can use the Python built-in `len()`

function or the `numpy.ndarray.shape`

property to get the number of columns of a 2d Numpy array.

The following is the syntax –

# num columns using the len() function len(ar[0]) # num columns using the .shape property ar.shape[1]

Let’s now look at both the methods in detail with the help of some examples –

First, we will create a 2d Numpy array that we will be using throughout this tutorial.

import numpy as np # create a 2d array ar = np.array([ [1, 2, 3, 4], [1, 1, 0, 0], [5, 6, 7, 8] ]) # display the array print(ar)

Output:

[[1 2 3 4] [1 1 0 0] [5 6 7 8]]

Here, we used the `numpy.array()`

function to create a 2d array with three rows and four columns.

### Method 1 – Number of columns using the `len()`

function

`len()`

is a Python built-in function that returns the length of an object. It is used on sequences or collections.

You can think of each row in a 2d Numpy array as a 1d array. If you apply the `len()`

function on the first row (or any row for that matter) you’ll get the number of values in that row which is equal to the number of columns in the array.

# number of columns of array print(len(ar[0]))

Output:

4

We get the number of columns in the above array as 4.

### Method 2 – Number of columns using the `.shape`

property

You can also get the number of columns in a 2d Numpy array by accessing its `.shape`

property which returns the tuple `(row_count, column_count)`

. To only get the column count, access the value at index 1 from the shape property.

# number of columns of array print(ar.shape[1])

Output:

4

We get the same result as above, 4.

## Summary

In this tutorial, we looked at two methods to get the column count for a 2d array in Numpy.

- Use the Python built-in
`len()`

function. (Apply it on any row in the array) - Via the
`.shape`

property of the array. (Value at index 1 in the shape tuple is the column count)

You might also be interested in –

- Numpy – Create a Diagonal Matrix (With Examples)
- Get the First N Columns of a 2D Numpy Array
- Get the Last N Columns of a 2D Numpy Array

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**