Array Basics¶

In [1]:
%pip install numpy
import numpy as np
np.__version__
Requirement already satisfied: numpy in /home/samrat/Documents/numpy-torch-tutorials/venv/lib/python3.8/site-packages (1.24.4)
Note: you may need to restart the kernel to use updated packages.
Out[1]:
'1.24.4'
In [9]:
arr = np.array([10, 20, 30, 40, 50])
print(arr)
print(arr.ndim)
print(arr.shape)
print(len(arr))
[10 20 30 40 50]
1
(5,)
5
In [15]:
arr_2d = np.array([[10,20,30,40,50], [100,200,300,400,500]])
print(arr_2d)
print(arr_2d.ndim)
print(arr_2d.shape)
print(len(arr_2d))
print(arr_2d.size)
print(arr.dtype)
[[ 10  20  30  40  50]
 [100 200 300 400 500]]
2
(2, 5)
2
10
Out[15]:
dtype('int64')
In [7]:
foo = np.array([1, 'hello', 2])
print(foo)

foo[0] = 'very very very very very very long string'
print(foo)
['1' 'hello' '2']
['very very very very v' 'hello' '2']
In [8]:
np.array([[1,2,3,4], [1.1, 2.2,3.3,4.4]])
Out[8]:
array([[1. , 2. , 3. , 4. ],
       [1.1, 2.2, 3.3, 4.4]])
In [9]:
np.array([[1,2,3,4], [1,2]])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[9], line 1
----> 1 np.array([[1,2,3,4], [1,2]])

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.