πŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Expert Masterclasses.
πŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///
⚑ Total XP: 0|πŸ’» python XP: 0

NumPy Array Indexing in Python

Learn about NumPy Array Indexing in this comprehensive Python tutorial. Learn how to access array elements using 1-D, 2-D, and 3-D indices, and discover the power of negative indexing.

LOADING ENGINE...

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

Select an unlocked node to view details root

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.

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'.

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Lesson Glossary

[01]Index

The numerical position of an element in an array, starting at 0.

Code Preview
// Index context

[02]Negative Indexing

Accessing an array from the end backward, where -1 represents the final element.

Code Preview
// Negative Indexing context

[03]Mutation

Changing the value of an existing array element in memory.

Code Preview
// Mutation context

Continue Learning