TypeError: list indices must be integers or slices, not list
Asked Answered
P

2

21

array = some kind of list with 3 columns and unlimited amount of rows with data inside of it.

Volume = array[0][2] 
counter = 0
for i in array: 
    if Volume == array[i][2]: #<------ why is this line a problem? 
        counter += 1
Philomena answered 19/5, 2016 at 16:58 Comment(1)
Does this answer your question? Why do I get an IndexError (or TypeError, or just wrong results) from "ar[i]" inside "for i in ar"?Culmiferous
S
18

This is a classic mistake. i in your case is already an element from array (i.e. another list), not an index of array (not an int), so

if Volume == i[2]:
    counter += 1

You can check the Python tutorial. Also, try doing this:

for i in array:
    print (i)

And see what you get!

Also I would advise to stick to naming conventions: variables are normally lower-case (volume, not Volume). In this case i is misleading. row or elem would be much more suitable.

Somatology answered 19/5, 2016 at 17:14 Comment(0)
F
8

Also, as this may happen frequently, note that you cannot access slices of lists (but you can for an array):

import numpy as np
integerarray = np.array([33,11,22], dtype=int)
integerlist = [33,11,22]
indexArray = [1,2,0]  # or equivalently, an array, e.g. np.argsort(integerlist)
print(integerarray[indexArray]) ## works fine
print(integerlist[indexArray])  ## triggers: TypeError: list indices must be integers or slices, not list

I hope this helps. It even happened to me that I had to convert to a float array, otherwise the object would remain of the wrong type.

Flatter answered 25/7, 2019 at 10:7 Comment(1)
fplandes, I have the same problem, for a moment my code was working, I have made some alterations in other functions, and now it throws the TypeError. lamb_func = lambda x,f,v: [x['data']['q']['57']['dt'], x['data']['q']['57']['meta'][f][v]['s']] i pass an x (dictionary), f (string) and v (string) arguments. How can one solve it, without amending the lamb_func to return results?Decarbonize

© 2022 - 2024 — McMap. All rights reserved.