NUMPY Tutorial



NumPy CREATING ARRAYS


🧱 NumPy – Creating Arrays

Creating arrays is the first step in working with NumPy. Arrays can be created from Python lists or using special functions offered by NumPy.

✅ Creating Array from List

You can convert a list or tuple into a NumPy array using np.array().

import numpy as np

# From a Python list
arr = np.array([10, 20, 30])
print(arr)

Output:

[10 20 30]

📏 Creating Multi-Dimensional Arrays

# 2D Array (Matrix)
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr2d)

Output:

[[1 2 3]
 [4 5 6]]

🔁 Using NumPy Array Creation Functions

NumPy provides several built-in functions to create arrays quickly:

  • np.zeros() – Array of all zeros
  • np.ones() – Array of all ones
  • np.full() – Array filled with a constant
  • np.eye() – Identity matrix
  • np.arange() – Array with a range of values
  • np.linspace() – Evenly spaced values over a range
np.zeros((2, 3))        # 2x3 array of zeros
np.ones((3,))           # 1D array of ones
np.full((2, 2), 7)      # 2x2 array with all values 7
np.eye(3)               # 3x3 identity matrix
np.arange(1, 10, 2)     # [1 3 5 7 9]
np.linspace(0, 1, 5)    # [0.  0.25  0.5  0.75  1. ]

🧠 Data Type Specification

You can specify the data type using the dtype parameter:

arr = np.array([1, 2, 3], dtype='float32')
print(arr)

🌀 Create Random Arrays (Optional)

NumPy also provides methods to create arrays with random values:

np.random.rand(2, 2)       # Random floats in [0, 1)
np.random.randint(1, 10, 5) # Random integers from 1 to 9
Note: All created arrays are of type numpy.ndarray, and they are more efficient than Python lists.
✅ Ready to move on? Next: NumPy Array Indexing and Slicing ➡️

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review