1

I have come accross a line code that actually works for the work I am doing but I do not understand it. I would like someone to please explain what it means.

b=(3,1,2,1)

a=2

q=np.zeros(b+(a,))

I would like to know why length of q is always the first entry of b.

for example len(q)=3

if b=(1,2,4,3) then len(q)=1

This is really confusing as I thought that the function 'len' returns the number of columns of a given array. Also, how do I get the number of rows of q. So far the only specifications I have found are len(q), q.size( which gives the total number of elements in q) and q.shape(which also I do not quite get the output, because in the latter case, q.shape=(b,a)=(1,2,4,3,2).

Is there function that could return the size of the array in terms of the numberof columns and rows? for example 24x2?

Thank you in advance.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Stevy KUIMI
  • 47
  • 2
  • 6
  • 1
    Possible duplicate of [Numpy array dimensions](https://stackoverflow.com/questions/3061761/numpy-array-dimensions) – David C. Jun 13 '18 at 00:11

2 Answers2

2

In Python a array does only have one dimension, that's why len(array) returns a single number.

Assuming that you have a 'matrix' in form of array of arrays, like this:

1 2 3

4 5 6

7 8 9

declared like

mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

you can determine the 'number of columns and rows' by the following commands:

rows = len(mat)
columns = len(mat[0])

Note that it only works if number of elements in each row is constant

Mario Campos
  • 323
  • 1
  • 2
  • 8
0

If you are using numpy to make the arrays, another way to get the column rows and columns is using the tuple from the np.shape() function. Here is a complete example:

import numpy as np
mat = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
rownum = np.shape(mat)[0]
colnum = np.shape(mat)[1]
wooshuwu
  • 133
  • 1
  • 3