011. 1-D Indexing and Negative Indices
EXECUTIVE_SUMMARY // AEO_OPTIMIZED
[Answer Engine Overview: What, Why & How]
For a 1-D vector, NumPy behaves exactly like standard Python lists. The index is 0-based.
arr[0] gets the first element.
arr[-1] gets the last element. Negative indices count backward from the end, which is extremely useful when you don't know the exact length of the array.
022. 2-D Indexing (Matrices)
To access elements in a 2-D array (matrix), use comma-separated indices representing the dimension axes. The format is array[row, column].
```python
matrix = np.array([[1, 2], [3, 4]])
print(matrix[0, 1]) # Returns 2
`
While matrix[0][1] works in Python, matrix[0, 1] is highly optimized in C and avoids creating temporary arrays in memory.
033. Mutating Elements
NumPy arrays are mutable. You can change the value of an element by assigning a new value to its index: arr[0] = 50. However, remember the dtype. If you have an integer array and try arr[0] = 3.14, NumPy will truncate the decimal and store 3, maintaining the integer homogeneity.
?Frequently Asked Questions
Why should I use arr[0, 1] instead of arr[0][1]?
Performance. `arr[0][1]` first creates a temporary 1-D array (`arr[0]`) in memory, and then accesses the second element (`[1]`). `arr[0, 1]` jumps directly to the exact memory location of the element in the C-array.
What happens if I use an index that is out of bounds?
You will trigger an `IndexError: index X is out of bounds for axis 0 with size Y`. NumPy enforces strict boundary checking.
Can I use negative indexing on 2-D arrays?
Absolutely. `matrix[-1, -2]` is perfectly valid. It means 'fetch the last row, and the second-to-last column'.
