Reputation: 774
I'm new to python and not understanding why this for loop won't work.
i = np.random.uniform(0,1,100)
# this does not give error
print(i[0])
print(i[1])
print(i[2])
# this gives error
for x in i:
print( i[x] )
I figure it's something to do with the line for x in i:
. So what would be the proper way to loop through i?
Upvotes: 0
Views: 198
Reputation: 559
In for x in i:
, x
will be every elements in i
. So your loop statement should be
for x in i:
print( x )
If you want x
to be the index, you should use the following code so that x
would be from 0 to the len(i)-1 (all the index of i
):
for x in range(len(i)):
print( i[x] )
In addition, I recommend you to use x as the name of the array and i as the index, which is integer.
Upvotes: 1