You get prettier code with:
for iy, ix in np.ndindex(a.shape):
print(a[iy, ix])
resulting in:
1
2
3
4
5
6
7
8
9
10
11
12
Answer from Markus Dutschke on Stack OverflowYou get prettier code with:
for iy, ix in np.ndindex(a.shape):
print(a[iy, ix])
resulting in:
1
2
3
4
5
6
7
8
9
10
11
12
a.shape[0] is the number of rows and the size of the first dimension, while a.shape[1] is the size of the second dimension. You need to write:
for x in range(0, rows):
for y in range(0, cols):
print a[x,y]
Note how rows and cols have been swapped in the range() function.
Edit: It has to be that way because an array can be rectangular (i.e. rows != cols). a.shape is the size of each dimension in the order they are indexed. Therefore if shape is (10, 5) when you write:
a[x, y]
the maximum x is 9 and the maximum y is 4.
x and y are actually poor names for array indices because they do not represent cartesian coordinates, but a location in memory. You can use i and j instead:
for i in range(0, rows):
for j in range(0, cols):
print a[i,j]
The documentation is a bit long but has a good, in-depth description of indices and shapes.
A quick question about iterating through 2d arrays with Python.
Is there a NumPy'-thonic'/efficient way to iterate over each elem in a 2D array?
Why can't I easily loop over numpy arrays
Looping over first two indices in 4-Dimensional Array?
This is melting my brain for whatever reason...
so if I have a 2d list like:
list = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
How would I just extract a certain index of every list?
I know I can do a list comprehension of
[i[0] for i in list]
beside using modules and imports is there any way to do this normally with a for loop?????
Thanks in advance