w3resource

NumPy: Create and display every element of a numpy array

NumPy: Array Object Exercise-70 with Solution

Write a NumPy program to create and display every element of a NumPy array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a 1-dimensional array 'x' with values from 0 to 11 and reshaping it into a 3x4 array
x = np.arange(12).reshape(3, 4)

# Using a loop with np.nditer to iterate through each element in the array 'x' regardless of its dimension
# Printing each element followed by a space and keeping the output in the same line due to the 'end' parameter
for x in np.nditer(x):
    print(x, end=' ')

# Printing a newline character to move to the next line after the loop completes
print()

Sample Output:

0 1 2 3 4 5 6 7 8 9 10 11   

Explanation:

In the above code –

‘x = np.arange(12).reshape(3, 4)’ creates a 1D NumPy array with elements from 0 to 11 using np.arange(), and then reshapes it into a 3x4 array using reshape(3, 4) and stores it in the variable ‘x’.

for x in np.nditer(x):: This line iterates through each element in the reshaped array using np.nditer(). np.nditer() is a NumPy iterator object that allows efficient iteration over elements in a NumPy array.

print(x, end=' '): Inside the loop, this line prints the current element followed by a space (the end=' ' argument ensures that the elements are printed on the same line separated by spaces)

Python-Numpy Code Editor:

Previous: Write a NumPy program to create an array with 10^3 elements.
Next: Write a NumPy program to create and display every element of a numpy array in Fortran order.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-70.php