Accessing arrays

The NumPy array interface is, on a shallow level, similar to that of Python lists. NumPy arrays can be indexed using integers and iterated using a for loop:

    A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])     A[0]     # Result:    # 0     [a for a in A]     # Result:    # [0, 1, 2, 3, 4, 5, 6, 7, 8] 

In NumPy, array elements and sub-arrays can be conveniently accessed by using multiple values separated by commas inside the subscript operator, []. If we take a (3,3) array (an array containing three triplets), and we access the element with index 0, we obtain the first row, as follows:

    A = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])     A[0]     # Result:    # array([0, 1, 2]) 

We can index the row again by adding another index separated by a comma. To get ...

Get Advanced Python Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.