Reputation: 31
Here is my list of lists and I'm trying to print a certain element:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[..., 0:1])
I get a
TypeError: list indices must be integers or slices, not tuple
Upvotes: 0
Views: 1559
Reputation: 316
You have to do this:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[0][0:1])
boxes_preds[0]
returns the first list in the boxes_preds
, and then you use your slicing / index to access the elements of that list.
You would do the same to access later elements of boxes_preds
, such as boxes_preds[1]
to access the second list.
Upvotes: -1
Reputation: 9377
You can imagine the index as 2D coordinates written in form [y][x]
.
Like when the nested lists represent a 2D matrix:
y / x
| 1, 300, 400, 250, 350
| 0, 450, 150, 500, 420
Where x
and y
both must be integers or in slice-notation:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[0][0]) # integer index for both
# 1
print(boxes_preds[-1][0:2]) # last of outer list, slice index for inner
# [0, 450]
There is a way to use tuples to index. As data-structure to store a 2D-index, but not as tuple inside the brackets:
coordinates_tuple = (1,1) # define the tuple of coordinates (y,x)
y,x = coordinates_tuple # unpack the tuple to distinct variables
print(boxes_preds[y][x]) # use those in separate indices
# 450
See Python - using tuples as list indices.
...
The ellipsis (three dots) is a special syntax element used in Numpy or as output representation in Python.
However it is not allowed as list-index. Following example demonstrates the error:
boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[...])
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not ellipsis
See:
Upvotes: 1
Reputation: 388
Your syntax is incorrect, use following syntax to get the elements inside list:
list_name[index_of_outer_list_item][index_of_inner_list_item]
so by that if you want let's say 300 of 1st list inside the outer list:
boxes_preds[0][1]
this should do it.
Upvotes: 2