NUMPY BASIC EXERCISE 20


Use a for loop over an array and print each element of the array separately.

In this exercise, we are going to loop over an array and print elements separately.

Note: arange([start,] stop[, step,], dtype=None) Return evenly spaced values within a given interval. Values are generated within the half-open interval “[start, stop)“ (in other words, the interval including `start` but excluding `stop`). For integer arguments the function is equivalent to the Python built-in `range` function, but returns an ndarray rather than a list.

Code: Loop Over An Array

import numpy as np
arr = np.arange(0,50).reshape((5,10))
print("Initial array")
print(arr)
print("Applying the for loop")
for a in np.nditer(arr):
    print(a)

Output

Initial array
[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]
 [20 21 22 23 24 25 26 27 28 29]
 [30 31 32 33 34 35 36 37 38 39]
 [40 41 42 43 44 45 46 47 48 49]]
Applying the for loop
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

Code Editor

import numpy as np arr = np.arange(0,50).reshape((5,10)) print("Initial array") print(arr) print("Applying the for loop") for a in np.nditer(arr): print(a)