Home > Back-end >  List of lists TypeError: list indices must be integers or slices, not tuple
List of lists TypeError: list indices must be integers or slices, not tuple

Time:07-09

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

CodePudding user response:

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.

CodePudding user response:

Indexing multi-dimensional lists

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]

Using a tuple to index a nested list

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.

Ellipsis ...

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:

CodePudding user response:

You have to do this:

boxes_preds = [[1, 300, 400, 250, 350],[0, 450, 150, 500, 420]]
print(boxes_preds[...][0:1])

boxes_preds[...] returns a list in the boxes_preds, and then you use your slicing / index to access the elements of that list.

  • Related