I am trying to find first_row = [1, 2, 3, 4, ...]
Currently, I have list = [[1, a], [2, b], [3, c], [4, d], ...]
and tried running: list[:, 0]
Output error: TypeError: List indices must be integer must be integer, not tuple
I am trying to find first_row = [1, 2, 3, 4, ...]
Currently, I have list = [[1, a], [2, b], [3, c], [4, d], ...]
and tried running: list[:, 0]
Output error: TypeError: List indices must be integer must be integer, not tuple
list doesn't support multiple (i.e. "comma-separated") indices, so you need something like
[sublist[0] for sublist in list]
The most popular alternative supporting multiple indexing like you tried is numpy's multidimensional array
The reason why list cannot do this is because it is a general container, so it cannot imply what you store inside. You might have
values = [[1, 2], 'three', MyClass(4, 5, 6), None]
Applying [0, :] to this would make no sense, the same way as it doesn't in most cases.
The subscript lst[:,0] does not do what you think it does. You might be used to pandas or other libraries which support indexing in multidimensional matrices, but the builtin list does not support this.
Instead, you should use a list-comprehension.
first_row = [column[0] for column in lst]
This is a shorthand for the following more verbose expression.
first_row = []
for column in lst:
first_row.append(lst[0])
In other words, you cannot vectorize multi-indexing with the list type. You have to recover each column one by one and the first element of each of those independently.
As a sidenote, try avoiding calling you variables list as it shadows the builtin of the same name.
first_row = [i[0] for i in list]
Edit: Since there are already two answers as this one, let me show a different one if you want to use slicing. First of all you SHOULDN'T use list as the name of your variable, since list is a reserved word in python. Suppose your list is called list1, you can do:
first_row = list(np.array(list1)[0,:].astype(int))