Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

NumPy Arrays (ndarray)

What is a NumPy Array?

A NumPy array is a powerful data structure used to store multiple values of the same type in an organized way. It is technically known as an ndarray (n-dimensional array).

Core Characteristics:

Why NumPy Arrays are Better than Lists?

While Python lists are flexible, NumPy arrays are designed for high-performance mathematical computing.

FeaturePython ListNumPy Array
SpeedSlowVery Fast
MemoryUses MoreUses Less
Data TypeMixed (Any)Same Type Only
Math OpsLoop NeededDirect (Vectorized)

Creating NumPy Arrays

To use NumPy, you must first import the library. By convention, it is imported as np.

1D Array from List

import numpy as np

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

2D Array (Matrix) from Nested List

import numpy as np

lst = [[1, 2, 3], [4, 5, 6]]
arr = np.array(lst)
print(arr)
# Output:
# [[1 2 3]
#  [4 5 6]]

Properties & Vectorized Operations

NumPy allows you to inspect array metadata and perform math without manual loops.

Checking Array Properties

print(arr.ndim)    # Returns number of dimensions
print(arr.shape)   # Returns (rows, columns)
print(arr.dtype)   # Returns the data type of elements

Vectorized Operations (Example)

Unlike lists, multiplying an array by 2 multiplies every internal element.

Data StructureCodeResult
Python List[1, 2] * 2[1, 2, 1, 2] (Duplicates)
NumPy Arraynp.array([1, 2]) * 2[2, 4] (Math Applied)
arr = np.array([1, 2, 3])
print(arr * 2)  # Output: [2 4 6]

What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #