011. The Slicing Formula
EXECUTIVE_SUMMARY // AEO_OPTIMIZED
[Answer Engine Overview: What, Why & How]
The syntax is [start:end:step].
- →start: The index where the slice begins (inclusive).
- →end: The index where the slice stops (exclusive).
- →step: Determines the increment between each index.
If you omit start, it defaults to 0. If you omit end, it defaults to the length of the array.
022. Slicing Multi-Dimensional Arrays
To slice a matrix, you slice both the rows and the columns, separated by a comma: matrix[row_slice, col_slice].
For example, matrix[:, 1:3] means 'Take ALL rows (:), but only columns 1 to 2'. This is heavily used in machine learning to separate target labels (the last column) from input features (the rest of the columns).
033. Views vs Copies
In standard Python, slicing a list creates a brand new copy in memory. In NumPy, slicing returns a View. It points to the original array's memory address to save processing time and RAM. If you alter the sliced view, the original array is modified. If you need a true independent copy, you must explicitly call .copy(), e.g., arr[1:4].copy().
?Frequently Asked Questions
Why does NumPy return a view instead of a copy when slicing?
NumPy is designed to handle massive datasets. If slicing a 10GB array created a copy by default, it would instantly consume another 10GB of RAM and crash your machine. Views allow you to manipulate huge chunks of data instantly and safely.
How do I reverse an array using slicing?
You can reverse an array by using a negative step size: `arr[::-1]`. This means 'start from the end, go to the beginning, stepping backwards by 1'.
Is the end index in a slice inclusive or exclusive?
It is always exclusive. The slice `[0:5]` will extract indices 0, 1, 2, 3, and 4, but it will stop before index 5.
