[Tutor] IndexError: index out of bounds
Peter Otten
__peter__ at web.de
Wed Mar 27 19:05:11 CET 2013
Sayan Chatterjee wrote:
> Hi Walter,
> Thanks a lot!
>
> Yes, now I get your point. append is working perfectly fine.
>
> Hi Peter:
>
> Exactly. It's very nice. Indices needn't have to be mentioned explicitly.
> No explicit looping and the thing is done!
>
> But I have a question, whenever we want to do operations on the individual
> array elements, don't we have to mention the indices explicitly i.e
> p_za[i]?
For Python's built-in list, yes, but not for numpy arrays.
> 1) Traceback (most recent call last):
> File "ZA.py", line 44, in <module>
> p_za = p_za % 4
> TypeError: unsupported operand type(s) for %: 'list' and 'int'
>>> items = [3, 4, 5]
>>> items % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'list' and 'int'
>>> items = numpy.array(items)
>>> items % 2
array([1, 0, 1])
Even for lists you can do better than using an explicit index, you can
iterate over its members:
>>> items = [3, 4, 5]
>>> [v % 2 for v in items]
[1, 0, 1]
> 2) Traceback (most recent call last):
> File "ZA.py", line 43, in <module>
> if p_za[i] > 4.0:
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
>
> When the i indices are removed * (1) * error message is showing up and
> when i is included *(2) *is shown.* *
You are probably seeing that error because p_za[i] is a numpy.array, i. e.
you have a list of arrays:
>>> items = [numpy.array([1,2]), numpy.array([3,4])]
>>> items[0] > 4
array([False, False], dtype=bool)
>>> if items[0] > 4: pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
How you managed to get there and what you actually want to achieve -- I
can't tell from what you provide. Perhaps you can give a little more
context, in code, but more importantly in prose.
More information about the Tutor
mailing list