The most intuitive way to begin using NumPy is by converting native Python sequences—such as lists and tuples—into multidimensional NumPy arrays using the np.array() factory function.
1. Creating 1D Arrays (Vectors)
A 1D array corresponds mathematically to a vector (a sequence of values with a single dimension):
1import numpy as np
2
3# From a Python list
4scores =[85,92,78,90,88]
5arr_1d = np.array(scores)
6
7print(arr_1d)# [85 92 78 90 88]
8print(type(arr_1d))# <class 'numpy.ndarray'>
9print(arr_1d.ndim)# 1 (One dimension)
10print(arr_1d.shape)# (5,) (Length of 5 elements)
Notice: When printed, NumPy arrays do not display commas between elements (unlike Python lists [85, 92, ...]), visually distinguishing them as mathematical matrices.
Click to Zoom
Anatomy of NumPy Ndarrays
2. Creating 2D Arrays (Matrices)
A 2D array corresponds to a matrix or a tabular spreadsheet with rows and columns, created by passing a nested list of lists:
1matrix_data =[
2[10,20,30],
3[40,50,60],
4[70,80,90]
5]
6
7matrix = np.array(matrix_data)
8
9print(matrix)
10# [[10 20 30]
11# [40 50 60]
12# [70 80 90]]
13
14print(matrix.ndim)# 2 (Two dimensions: Rows and Columns)
15print(matrix.shape)# (3, 3) (3 rows, 3 columns)
The Inhomogeneous Trap:
Every sub-list in a 2D array must have identical length! If you pass [[1, 2], [3, 4, 5]], modern NumPy raises a ValueError because it cannot form a rectangular contiguous C-array.
3. Creating 3D Arrays (Tensors / Batches / Color Images)
A 3D array adds a depth dimension, represented as a list of lists of lists. In machine learning, 3D arrays represent batches of matrices or RGB color images:
1# 2 layers, each having 3 rows and 4 columns: shape (2, 3, 4)
2tensor_3d = np.array([
3[
4[1,2,3,4],
5[5,6,7,8],
6[9,10,11,12]
7],
8[
9[13,14,15,16],
10[17,18,19,20],
11[21,22,23,24]
12]
13])
14
15print(tensor_3d.ndim)# 3
16print(tensor_3d.shape)# (2, 3, 4)
17print(tensor_3d.size)# 24 total elements
4. Specifying Explicit Data Types on Creation
You can dictate the memory precision upon array creation using the dtype parameter:
1# Force floating-point representation
2floats = np.array([1,2,3,4], dtype=np.float32)
3print(floats)# [1. 2. 3. 4.]
4
5# Force 8-bit unsigned integers (0 to 255, perfect for image pixels!)
6pixels = np.array([0,128,255], dtype=np.uint8)
Interactive Quiz• Knowledge Check
Multiple Choice Questions
Question 1
What function is used to convert a native Python list or tuple into a NumPy ndarray?
Question 2
What will be the 'shape' attribute of 'np.array([[1, 2, 3], [4, 5, 6]])'?
Question 3
How does the console print output of a NumPy array visually differ from a standard Python list?
Question 4
What happens if you try to create an array with ragged sub-lists of inconsistent lengths: 'np.array([[1, 2], [3, 4, 5]])' in modern NumPy?
Question 5
Which parameter in 'np.array()' allows you to explicitly enforce a 32-bit floating point data type?