Search code examples
pythonlistloopsnested-liststraversal

How to find index of a given value in a nested list in Python?


I wat to traverse over the nested list below, find 1 then print index of that list.

my_list = [['Hello', 'World','!'],[1, 3, 'Test', 5, 7],[2, 4]]

for item in range(len(my_list)):
    for item2 in range(len(my_list[item])):
        output = my_list[item][item2]
        if output == 1:
            print('the index of 1 is [%d][%d] ' % (item.item2))

The loops above returned AttributeError: 'int' object has no attribute 'item2'

Can anyone tell me how to fix it? Thank you for the help!


Solution

  • Everything seems fine in your code, just make the string formatter a tuple. Modify the last line of your code to this below:

    print('the index of 1 is [%d][%d] ' % (item,item2))