NumPy Creating Arrays

📌 NumPy — Creating Arrays

NumPy provides multiple ways to create arrays depending on your needs. The most common method is using the np.array() function, but NumPy also includes built-in methods for creating:

✔ zeros
✔ ones
✔ sequences
✔ random values
✔ identity matrices
✔ custom ranges


🧩 1. Creating Array Using np.array()

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)

Output:

[1 2 3 4 5]

Multi-Dimensional Array

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

⚙ 2. Creating Arrays with Built-In Functions

🔹 zeros(): Create array of zeros

np.zeros(5)

Output:

[0. 0. 0. 0. 0.]

2D zeros array:

np.zeros((2, 3))

🔹 ones(): Create array of ones

np.ones((3, 3))

Output:

[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]


🔹 full(): Create array with a given value

np.full((2, 3), 7)

Output:

[[7 7 7]
[7 7 7]]


🔢 3. Creating Number Sequences

🔹 Using arange() (like Python range)

np.arange(1, 10, 2)

Output:

[1 3 5 7 9]

🔹 Using linspace() (evenly spaced values)

np.linspace(0, 1, 5)

Output:

[0. 0.25 0.5 0.75 1. ]

🔁 4. Identity & Eye Matrices

🔹 identity()

np.identity(4)

Output:

[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

🔹 eye() (identity with control over diagonal shift)

np.eye(3, k=1)

🎰 5. Random Arrays

np.random.rand(3, 3)

Random integers:

np.random.randint(1, 100, size=5)

📏 6. Creating Empty Array (Uninitialized memory)

⚠ Values are random (not zeros).

np.empty(5)

🧠 Summary Table

Method Purpose
np.array() Create array from list or tuple
np.zeros() Array filled with zeros
np.ones() Array filled with ones
np.full() Array with user-defined value
np.arange() Create numeric range
np.linspace() Create evenly spaced range
np.identity() Identity matrix
np.eye() Identity-like matrix
np.random.rand() Random values
np.random.randint() Random integers
np.empty() Empty (uninitialized) array

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *