97

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.

Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110

6 Answers6

180

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

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 6
    So long as it's not a jagged array, this is ideal. – Makoto May 23 '12 at 03:21
  • yo, I want to find sum of all element in that 2D array def sum1(input): sum = 0 for row in range (len(input)-1): for col in range(len(input[0])-1): sum = sum + input[row][col] return sum print sum1([[1, 2],[3, 4],[5, 6]]) It display 4 instead of 21 (1+2+3+4+5+6 = 21). Where is my mistake? – Ronaldinho Learn Coding May 23 '12 at 03:39
  • 1
    There's a simpler solution: sum(sum(x) for x in input) – Óscar López May 23 '12 at 03:41
  • 1
    @LongBodie: The mistake is that you subtract 1 from the lengths where you shouldn't. `Range(n)` already gives 0,1,...,**n-1** . – Junuxx May 23 '12 at 04:46
43

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.

Akavall
  • 82,592
  • 51
  • 207
  • 251
26

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

sum(len(x) for x in input)
MattNo
  • 271
  • 3
  • 6
  • Great, this was exactly what I needed! In my case I can count all elements of a list up to 2nd degree: sum(len(x) if isinstance(x, list) else 1 for x in some_list) – Bjarne Magnussen Sep 29 '17 at 06:21
11

Assuming input[row][col],

    rows = len(input)
    cols = map(len, input)  #list of column lengths
machow
  • 1,034
  • 1
  • 10
  • 16
1

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

Riya Das
  • 11
  • 1
0

assuming input[row][col]

rows = len(input)
cols = len(list(zip(*input)))
Miae Kim
  • 1,713
  • 19
  • 21