I want to know how many rows and columns an array has in Python?

Asked

Viewed 3,780 times

1

I am trying to develop an exercise that requires the creation of a function that when it receives as a parameter an array, it returns the number of row and column that this matrix has.

I’m trying to do this with the code below, yet without being a function, but when I tried with smaller matrices went wrong.

n = [[1,2,3,44], [4,5,6,55], [7,8,9,77], [10,20,30,99], [40,50,60,54]]

contlin = 0
contcol = 0

for i in range(len(n)):
    contlin = contlin + 1

for j in range(i):
    contcol = contcol + 1
    print(j, end = ' ')
    print("\n")

print('Total:', contlin, 'X', contcol)
  • 3

    You tried to: len(n) for lines and len(n[0]) for the columns?

  • Remembering that this is not a "matrix" - it is a "list list" - it is a two-dimensional data structure, and therefore can be used as a matrix. But nothing would prevent, for example, someone making an "append" in the list of the 5th line, and only that line would have more elements. Python does not have a two-dimensional (or mulitdimensional) data native structure, but it is very easy to create a class for this. Usually, however, one uses the Numpy library that already has these very well defined objects.

5 answers

1

You can calculate the dimensions of your 2D matrix using basically the technique:

nlinhas = len(m)
ncolunas = len(m[0])

Note that the number of columns is calculated by obtaining the amount of elements present in the first row of the matrix, this leaves two questions open:

1) What if the matrix is empty? In this case there is no first line:

m = []
ncolunas = len(m[0]) #IndexError: list index out of range

2) And if the matrix has several lines of different sizes:

m = [ [1,2,3], [1,2], [1,2] ]
ncolunas = len(m[0]) # 3 ???

To get around this kind of problem, I suggest something like:

def obter_dimensao(m):
    # Verifica se todas as linhas da matriz
    # possuem o mesmo tamnho
    if len({len(i) for i in m}) > 1:
        raise TypeError('Matriz 2D invalida.')

    # Calcula quantidade de linhas na matriz
    linhas = len(m)

    # Se nao houverem linhas na matriz
    # assume zero colunas
    colunas = len(m[0]) if linhas else 0

    return (linhas, colunas)

m1 = []                  # 0x0
m2 = [[],[],[]]          # 3x0
m3 = [[1],[2],[3]]       # 3x1
m4 = [[1,2,3],[1,2,3]]   # 2x3
m5 = [[1,2,3],[1,2,3,4]] # Matriz invalida!

print(obter_dimensao(m1))
print(obter_dimensao(m2))
print(obter_dimensao(m3))
print(obter_dimensao(m4))
print(obter_dimensao(m5))

Exit:

(0, 0)
(3, 0)
(3, 1)
(2, 3)
Traceback (most recent call last):
  File "main.py", line 18, in <module>
    print(obter_dimensao(m5))
  File "main.py", line 3, in obter_dimensao
    raise TypeError('Matriz 2D invalida.')
TypeError: Matriz 2D invalida.

See working on Repl.it

0

There’s actually another way:

Matriz1 = [[1,2,3,4],[2,4,6,16],[4,8,12,45],[10,20,30,67],[1,2,3,67]]

Matriz2 = [[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]]

Matriz3 = [[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]]

Let’s assume the 3 matrices, above, non-square of order, respectively equal to: (5 X 4), (10 X 2) and (3 X 6).

A simple way to determine the amount of columns consists of:

1) Find the number of lines: nlinhas = len(Matriz)

2) Find quantity of elements: nElementos = len(Matriz[0])

3) Finally, the ncolunas = nElementos/nlinhas

The algorithm goes like this:

nlinhas = 0
nElementos = 0
#ncolunas = 0

for i in range(len(Matriz)):

    nlinhas += 1

    for j in range(len(Matriz[0])):

        nElementos += 1

ncolunas = (nElementos/nlinhas)

print('---------------------------------------------------------------------------------------------')
print('\nNúmero de linhas: ' +str(nlinhas)+'\n'  + '\nNúmero de colunas: '+str(ncolunas)+'\n')
print('---------------------------------------------------------------------------------------------')

If we use Matriz1, Matriz2 and Matriz3, in that order, we will find:

---------------------------------------------------------------------------------------------

Número de linhas: 5

Número de colunas: 4.0

---------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------

Número de linhas: 10

Número de colunas: 2.0

---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------

Número de linhas: 3

Número de colunas: 6.0

---------------------------------------------------------------------------------------------

0

The problem with your code is in the second loop for. What happens is that you count the number of columns, based on the number of rows. The result worked in this code using this matrix by pure coincidence, and I’ll explain why.

The number of lines that the matrix has is 5, then the return of range in the second repetition will be numbers of 0...4. Now if the matrix had 4 lines, the return would be numbers of 0...3.

To prove this, test remove a line from your matrix as in the example below:

Matrix:

n = [[1, 2, 3, 44], [4, 5, 6, 55], [7, 8, 9, 77], [10, 20, 30, 99]]

Output:

Total: 4 X 3

To count how many columns your matrix has, you must "enter" each row through the index of which, in this case, is the variable j of its second repetition.

One very important thing that we can notice, is that all rows have the same number of columns. Therefore, it is not necessary to scroll through the rows, just check the number of columns of a single row. See example below:

for linha in matriz: # Não é necessário o range() e o len() aqui.
    contlin = contlin + 1

linha = matriz[0]

for coluna in linha:
    contcol = contcol + 1

If you don’t want to do everything by hand, you can simply use the function len() to count the number of rows and columns, without needing a for loop.

See below the function I created to get the matrix size:

def obter_tamanho(matriz):

  linhas = len(matriz)
  colunas = len(matriz[0])

  return linhas, colunas


matriz = [[1, 2, 3, 44], [4, 5, 6, 55], [7, 8, 9, 77]]
tamanho = obter_tamanho(matriz)

print('Total: {} X {}'.format(*tamanho))

0

Matrix is a special case of two-dimensional list in which each data line has the same number of elements or is a list of lists of equal length.

Aware of this and how it was commented to get the number of rows and the number of columns of an array you can use the native python function len() which returns the number of elements of an object:

matriz = [[ 1, 2, 3,44], 
          [ 4, 5, 6,55], 
          [ 7, 8, 9,77], 
          [10,20,30,99], 
          [40,50,60,54]]

print (f'Número de linhas: {len(matriz)}')
print (f'Número de colunas: {len(matriz[0])}') #basta medir a primeira linha pois as outras terão o mesmo comprimento.

Code in the Repli.it: https://repl.it/repls/NextWhichBrain

Or use the library Numpy which is the fundamental package for scientific computing with Python that also provides functions to work with matrices and linear Algebra.

To create an array with Numpy use the function array() and to measure the length of the array on one of its axes use the function size() parameter axis setado in 0 for lines and 1 for columns.

import numpy as np

matriz = np.array([[ 1, 2, 3,44],
                   [ 4, 5, 6,55], 
                   [ 7, 8, 9,77], 
                   [10,20,30,99], 
                   [40,50,60,54]])

print (f'Número de linhas: {np.size(matriz, 0)}')
print (f'Número de colunas: {np.size(matriz, 1)}')

Code in the Repli.it: https://repl.it/repls/BluevioletLonelyBrackets

0

You can use the Numpy for that. There is a function inside called Shape and it is usually used to obtain the "form" of any matrix. For example:

from numpy import array

numpy_array = array([[1, 2, 3], [10, 15, 20]])

print(numpy_array.shape)

This will print something like this:

(2,3)

Where 2 refers to rows and 3 columns

Browser other questions tagged

You are not signed in. Login or sign up in order to post.