Home > Mobile >  Comparing array elements using for and if statement
Comparing array elements using for and if statement

Time:04-01

I have the following code:

import math
import numpy
import numpy as np
import numpydoc
import matplotlib
x= [1,2 ,3 ,4 ,5 ,6]
y= [5,6,7 ,8 ,9 ,10 ]

ax=np.array(x)
ay=np.array(y)
for i in ax:
    if ax[i]>4:
        print("Hi")
    else:
        print("Hello")

I am getting this error:

IndexError: index 6 is out of bounds for axis 0 with size 6

I want the code to check each value of the array and if the condition in the if statement is satisfied, then the program runs/

CodePudding user response:

Your issue is that you are iterating over the elements of the array, but then trying to use the element as the index. When you get to the last element of ax, you're trying to do ax[6], which is out of range for the size of ax.

You should do one or the other, ie:

for i in ax:
    if i > 4:
        print('Hi')
   else:
        print('Hello')

or

for i in range(len(ax)):
    if ax[i] > 4:
        print("Hi")
    else:
        print("Hello")

Depending on what your actual goal is here, a more pythonic approach could be a list comprehension:

res = ["Hi" if i > 4 else "Hello" for i in ax]

CodePudding user response:

I ran it as below.

x= [1,2,3,4,5,6]
y= [5,6,7,8,9,10]

ax=np.array(x)
ay=np.array(y)

for i in ax:
    if i>4:
        print("Hi")
    else:
        print("Hello")

enter image description here

CodePudding user response:

With this iteration pattern, I would suggest using np.where() as opposed to an explicit for loop:

import numpy as np

ax = np.array([1, 2, 3, 4, 5, 6])
result = np.where(ax > 4, "Hi", "Hello")
print("\n".join(result))

This outputs:

Hello
Hello
Hello
Hello
Hi
Hi

CodePudding user response:

The x Array element is not index so y[x[i]] can out of range.

You can use

for index, value in enumerate(x):
    y[index] # This is correct
    x[value] # This can produce same error :D

CodePudding user response:

Your iteration is wrong, even for a list. To illustrate:

In [321]: alist = ['ab','cd','ef']
In [322]: for i in alist:
     ...:     print(i)
     ...: 
ab
cd
ef

The iteration variable i is an element of the list, NOT an index.

In [323]: i
Out[323]: 'ef'
In [324]: alist[i]
Traceback (most recent call last):
  Input In [324] in <cell line: 1>
    alist[i]
TypeError: list indices must be integers or slices, not str

It does not make any sense to use it as an index. In your case the problem didn't become obvious until you hit the 6, but ax[i] was wrong even before that.

I've seen this mistake in a number of novice questions, and wonder why? Is it just carelessness, or is there some tutorial that's misleading people?

  • Related