Getting TypeError: list indices must be integers when using list[:,colIndex] to get column data as list

39 views Asked by At

I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.

for example:

lst = [[1,2,3],[10,12,13]]
lst[:,0]

Returns:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
TypeError: list indices must be integers

I don't understand...

Edit: Running this in Python 3.9 gives me:

TypeError: list indices must be integers or slices, not tuple
1

There are 1 answers

0
njminchin On

It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(

However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467