+2 votes
in Programming Languages by (73.8k points)

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

For this 2D list, when I use a[:,1] to select the elements of the second column, it gives the following error:

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

How to select the elements of any column of a 2D list?

1 Answer

+2 votes
by (348k points)
selected by
 
Best answer

Convert 2D list to Numpy array, then it will not give the error. When you use a[:,1], the Python list considers it as a tuple and hence it throws the error. Here is the example using Numpy array:

>>> import numpy as np
>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> b=np.array(a)
>>> b
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> b[:,1]
array([2, 5, 8])
>>> list(b[:,1])
[2, 5, 8]
>>> list(b[:,0])
[1, 4, 7]
>>> list(b[:,2])
[3, 6, 9]
>>>


...