1

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!

1
  • 2
    Instead of (item.item2) do (item, item2) Commented Jan 30, 2020 at 5:17

3 Answers 3

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1

I have used enumerate on the nested list to use both the index of the item in the list and the respective list item.

To find the index of an item use the list_name.index(value) method.

Use in to check the membership i.e. to check if a value is in the list.

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

for i, item in enumerate(my_list):
    if 1 in item:
        print('Index of 1 is [{}][{}]'.format(i,item.index(1)))

Output:

1 Comment

Not a functional problem, but I think i1, i2 would be a less confusing naming choice for the loop variables
0
for i in my_list:
    if 1 in i:
        print(str(i.index(1)) + "th element of " + str(i))

This outputs

0th element of [1, 3, 'Test', 5, 7]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.