102

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.

1
  • 4
    sounds like you should be using a numpy array, not a list of lists Commented May 23, 2012 at 5:27

6 Answers 6

185

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

Sign up to request clarification or add additional context in comments.

4 Comments

So long as it's not a jagged array, this is ideal.
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?
There's a simpler solution: sum(sum(x) for x in input)
@LongBodie: The mistake is that you subtract 1 from the lengths where you shouldn't. Range(n) already gives 0,1,...,n-1 .
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.

1 Comment

Thank you, I didn't want to use numpy for this thing
28

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

sum(len(x) for x in input)

1 Comment

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

Assuming input[row][col],

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

Comments

1

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

Comments

0

assuming input[row][col]

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.