w3resource

NumPy: Find the 4th element of a specified array

NumPy: Array Object Exercise-50 with Solution

Write a NumPy program to find the 4th element of a specified array.

Pictorial Presentation:

Python NumPy: Find the 4th element of a specified array

Sample Solution:

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array with specific data type (np.int32)
x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)

# Printing the original array
print(x)

# Accessing the fourth element (index 3) of the flattened array using the 'flat' attribute
e1 = x.flat[3]

# Printing the fourth element of the flattened array
print("Fourth element of the array:")
print(e1) 

Sample Output:

[[ 2  4  6]                                                            
 [ 6  8 10]]                                                           
Forth e1ement of the array:                                            
6 

Explanation:

In the above exercise –

x = np.array([[2, 4, 6], [6, 8, 10]], np.int32): This part creates a 2x3 array ‘x’ with the given list of lists, and sets the data type to np.int32.

e1 = x.flat[3]: The flat attribute of the array ’x’ returns a one-dimensional iterator over the elements of the array. The code then accesses the 4th element (index 3) of the flattened array using the index notation. Note that the elements are accessed in row-major order (C-order) by default.

print(e1): This line prints the value of the 4th element of the array, which is stored in the variable ‘e1’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to collapse a 3-D array into one dimension array.
Next: Write a NumPy program to interchange two axes of an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.