Iterating Through Numpy Array, Element Value Causing Out of Bounds?

Question:

I know this is something stupid… but I’m missing it. I’m trying to fill a numpy array with random values (1-10) and then iterate through the array to check those values. If I fill the array with values 1-9… no problem, if one of the values is ever 10… I get an out of bounds error.

When iterating through an array using:

for x in array:
     if array[x]==y: do_something_with_x

Is x not the element in the array? If that’s the case, why is my code referencing the value of x as 10 and causing the array to go out of bounds?

import numpy as np
import random

arr_orig = np.zeros(10)
arr_copy = np.copy(arr_orig)

arr_orig = np.random.randint(1,11,10)

lowest_val = arr_orig[0]

for x in arr_orig:
    if arr_orig[x] < lowest_val: lowest_val = arr_orig[x] 

arr_copy[0] = lowest_val

print (arr_orig)
print (arr_copy)
Asked By: user2059972

||

Answers:

As in the comment from @John Gordon, it’s an indexing problem. I think you meant:

for x in arr_orig:
    if x < lowest_val: lowest_val = x
Answered By: user19077881
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.