Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find length of 2D array Python

Tags:

python

arrays

How do I find how many rows and columns are in a 2d array?

For example,

Input = ([[1, 2], [3, 4], [5, 6]])` 

should be displayed as 3 rows and 2 columns.

like image 756
Ronaldinho Learn Coding Avatar asked May 23 '12 03:05

Ronaldinho Learn Coding


People also ask

How do you find the length of a 2D array?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

What does Len return in a 2D array?

2D Array or Matrix Calling len on a multi-dimension matrix will return the number of rows in that matrix.

How do you find the total number of elements in a 2D array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.

How do you find the number of rows in a matrix in Python?

The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.


2 Answers

Like this:

numrows = len(input)    # 3 rows in your example numcols = len(input[0]) # 2 columns in your example 

Assuming that all the sublists have the same length (that is, it's not a jagged array).

like image 164
Óscar López Avatar answered Oct 22 '22 09:10

Óscar López


You can use numpy.shape.

import numpy as np x = np.array([[1, 2],[3, 4],[5, 6]]) 

Result:

>>> x array([[1, 2],        [3, 4],        [5, 6]]) >>> np.shape(x) (3, 2) 

First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.

like image 45
Akavall Avatar answered Oct 22 '22 07:10

Akavall