How to Find the Number of Rows and Columns in an Array in Python


In this article, we show how to find the number of rows and columns in an array in Python.

Say, there is an existing array that you are dealing with in code. And we want to see the structure or layout of the array, how many rows and columns it has.

Python has a built-in way of allowing us to see teh row and column makeup of an array.

If we call the array.shape, we are able to see the shape of the array, or, rather, how many rows and columns the array has.

So let's go through a full example now below.

In the example below, we'll create an array and then show the structure, or layout, of the array in terms of its row and column composition.

So, first, we must import numpy as np, since we are using numpy to create an array.

Next, we create an array that goes from 0 to 29, so an array of 30 elements.

We then check to see the structure, or layout, of the array with the statement, array1.shape

In response, we get the output, (30,)

When the result is simply a single number followed by a comma, this means it is a one-dimensional array. There are no rows and columns. It's one-dimensional.

Now let's see what a 2-dimensional array would look like.

We rearrange our orignal one-dimensional array into a 2-dimensional array. We do this using the reshape() function. We reshape this one-dimensional array into a two-dimensional array that has 5 rows and 6 columns.

We then check the structure of the array using the statement, array1.shape

As output, we get (5,6)

This tells us that the array has 5 rows and 6 columns.

We then output the contents of the array and see an array that has 5 rows and 6 columns from 0 to 29.

And this is a way how you can check how many rows and columns an array has in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...