What's the purpose of a.shape and np.arange?

Week2: optional lab Python,Numpy & vectorization
I am sorry. I am beginner. So I have basic questions at time.
What is the purpose of a.shape? what is this .shape used for? Also, why do we write np.arange? when do we need it?
In the following code in the screenshot, a[2].shape: (). Why does it return this empty parenthesis?

1 Like

When you see a numpy call that is new to you, the first thing to do is read the documentation. You can find it by googling “numpy arange” in this case. Here’s the link I get from that search. You’ll find that it produces an array of evenly spaced values and you can control its behavior through the arguments.

If you’re going to call a function, the first thing to do is make sure you understand what the function does and how you control it through the arguments you pass it.

In the case of “shape”, that is a “method” of the class “numpy array”. I hope that you have enough experience with python to have gotten to the “object oriented programming” facilities in python. A “class” is a definition of a type of object. A “class” can have “attributes” that you reference as myClass.attribute and it can have “methods” which are functions that you can call as myClass.method(...).

Here’s the docpage for numpy array.

The shape of a numpy array is a python “tuple” which gives a list of the dimensions of the array, so you can see how many dimensions it has and their size. E.g. watch this:

A = np.ones((2,7))
v = np.ones((1,7)) * 2

(2, 7)
(1, 7)
[[0.5 0.5 0.5 0.5 0.5 0.5 0.5]
 [0.5 0.5 0.5 0.5 0.5 0.5 0.5]]

If the shape shows as (), that means the object is a 0 dimensional array or just a single scalar value. Try printing the shape of a in your example and you’ll see that it’s a 1D (one dimensional) array. If you index it as a[2] to select one entry of that array, then it is a 0D or scalar object.