Sam Sam - 6 months ago 31
Python Question

List index out of range? (Python)

I have an array that has lists as it's entries( for examply, array= ([1,2],[2,3],[3,4]) ), and I want to loop through these lists and compare a specific item to see if it matches a criteria, but I keep getting this error: "Indexerror: list index is out of range"

this is my code:

for i in enumerate(arr):
if arr([i][6]) == 0.0:
humans= humans+[arr[i,col]]

I have checked the actual array by printing out array[1][6] for example, and I know for a fact that there's a value there. So why won't it loop through ?


Your understanding of enumerate() is wrong. It returns the list of tuples with each item mapped to its index. Here is the value it returned in your case:

>>> list(enumerate(arr))
[(0, [1, 2]), (1, [2, 3]), (2, [3, 4])]

If want to iterate so that i will have value from 0 to length of arr, you need to use range() as:

for i in range(len(arr))

Also the content of your list is :

arr = [[1,2],[2,3],[3,4]]

It is a 3X2 list, and you are doing arr[i][6], it will give IndexError as length of each sub-list is just two