2

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.

1

2 Answers 2

3

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

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

1 Comment

this will not work if the matrix turns out to be 1-D
1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.