Find length of 2D array Python

PythonArrays

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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).

Solution 2 - Python

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.

Solution 3 - Python

In addition, correct way to count total item number would be:

sum(len(x) for x in input)

Solution 4 - Python

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths

Solution 5 - Python

You can also use np.size(a,1), 1 here is the axis and this will give you the number of columns

Solution 6 - Python

assuming input[row][col]

rows = len(input)
cols = len(list(zip(*input)))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRonaldinho Learn CodingView Question on Stackoverflow
Solution 1 - PythonÓscar LópezView Answer on Stackoverflow
Solution 2 - PythonAkavallView Answer on Stackoverflow
Solution 3 - PythonMattNoView Answer on Stackoverflow
Solution 4 - PythonmachowView Answer on Stackoverflow
Solution 5 - PythonRiya DasView Answer on Stackoverflow
Solution 6 - PythonMiae KimView Answer on Stackoverflow