Introduction to NumPy, Arrays and Array Operations

Theory

NumPy vs List:

NumPy: Optimized for numerical operations, uses contiguous memory, and supports multi-dimensional arrays. It’s faster and more memory-efficient than Python lists.

Python List: Flexible and general-purpose, but slower for numerical tasks and lacks built-in support for advanced operations.

NumPy Array Creation:

  • np.array(): Create an array from a list.
  • Iteration in NumPy:
  • Basic iteration: Loop through array elements, but NumPy allows faster vectorized operations without loops.
  • np.nditer(): Efficiently iterate over multi-dimensional arrays.
  • Slicing in NumPy

    Slicing in NumPy is a technique used to access a subset of elements from an array. It follows the syntax array[start:stop:step], and can be applied to both 1D and 2D arrays.

    1D Array Slicing In a 1D array, slicing allows you to extract a range of elements based on their indices.

    Basic Slicing: You can specify the start and stop indices.

    2D Array Slicing Slicing in 2D arrays works similarly, but you must specify slicing for both rows and columns.

  • Start Index: Specifies where the slice starts (inclusive).
  • Stop Index: Specifies where the slice ends (exclusive)
  • .
  • Step: Defines the interval between elements.
  • Negative Indexing: Allows you to count from the end of the array (e.g., -1 is the last element)