-->

Python - NumPy Part 1: Creating NumPy Arrays

NumPy arrays are the cornerstone of the library. They are multi-dimensional and highly efficient for numerical operations compared to standard Python lists.

Examples and Explanation

Creating Arrays from Lists

import numpy as np

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

print(array)  # Output: [1 2 3 4]

Explanation: This converts a Python list into a 1D NumPy array. NumPy arrays offer faster computations due to their fixed data type and contiguous memory allocation.

Creating Multi-Dimensional Arrays

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

print(matrix)

# Output:

# [[1 2 3]

#  [4 5 6]]

Explanation: Multi-dimensional arrays are ideal for matrix operations and handling tabular data.

Using Built-In Functions

zeros = np.zeros((3, 3))

print(zeros)

# Output:

# [[0. 0. 0.]

#  [0. 0. 0.]

#  [0. 0. 0.]]

Explanation: The zeros() function creates an array filled with zeros. Similar functions include ones() and empty().

Creating Arrays with arange()

sequence = np.arange(0, 10, 2)

print(sequence)  # Output: [0 2 4 6 8]

Explanation: Generates a sequence of evenly spaced values, which is useful for iterative computations.

Creating Arrays with Random Values

random_array = np.random.random((2, 3))

print(random_array)

Explanation: This creates arrays with random values, commonly used in simulations and testing.