Ho to solve: list indices must be integers or slices, not list

Hi guys!
I’ve found this issue:

Here is my code, I have two lists and a list that contains the two lists (my real lists are more complex but I’m trying to simplify them in order to focus on the main problem)


for i in list:
for j in list[i]:
…ecc, ecc…

I got this error message:
in line: “for j in list[i]”
list indices must be integers or slices, not list

I also tryed with
for j in range(len(list[i])

but I received the same message

Any advice?
Thank you in advance!

The index is the part within square brackets. So for list[i], your index is i. Python is telling you that the index must be an int or a slice, not a list.

In the for i in list: line, the variable i isn’t set to the place in the list, it’s set to each element in turn. So I suspect you were intending something closer to:

for i in list:
    for j in i:


I tried your suggestion:

for i in list:
for j in i:

but I get the same error message:
in → print(somma[i][j])
TypeError: list indices must be integers or slices, not list

Can you tell me how to solve?

What is somma? Again i and j are not indices. They are the members of the list. so you can just print the object.

for i in list:
    for j in i:

If you need the index because you’re inspecting some other data structure, you have to loop over a range or an enumerate of the object.

for i, sublist in enumerate(list):
    for j, item in enumerate(sublist):
        print(f"This item is {item} and the other item might be {somma[i][j]}")

I would be helpful to understand what is the objective of the code. What should it accomplish?

It is not good practice to use built-in list as name. Down the road something like this could happen:

>>> list('abc')
['a', 'b', 'c']
>>> list = [1, 2, 3]
>>> list('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

Thank you! I made a mistake with the indices.
But, now I have another issue: is it possible to get the name of the list a specific sublist comes from?

For example:


for i in list1:
for j in i:

I have to get, at a specific step of the loop, what is the list (a,b or c) a specific item comes from.
For example, if the algorithm gives me [4,5,6,2], I expect → ‘b’

You might want to look into dicts.

lists_of_lists = {
    'a': [[1,2,3], [1,4,5]],
    'b': [[8,6,5], []]
for lists_name, lists in lists_of_lists.items():
    # do something with the name/key
    for sublist in lists:
        # and so on

This might be helpful: