0

I have a nested list of different values (list x in the below code snippet). I also have a for loop that iterates over every index in the list, printing the indices between 0 and 2.

When I have a nested list of the same values (lists y and z in the below code snippet) the loop prints 0 three times.

x = [[1,2,3],[4,5,6],[7,8,9]]
y = [['X' for x in range(3)] for x in range(3)]
z = [['X', 'X' 'X'], ['X', 'X' 'X'], ['X', 'X' 'X']]

for i in x:
    print(x.index(i))

for i in y:
    print(y.index(i))

for i in z:
    print(z.index(i))

Why does the first loop produce 0, 1, and 2 and the second/third loop produce only zeroes? Thanks for your help.

1
  • What you're looking for is enumerate, not index. index is almost never the right tool for any job it's applied to. Commented Mar 14, 2022 at 23:01

2 Answers 2

1

.index() returns the index of the first instance of the argument that you pass in.

For the first for loop, since all the elements are unique, .index() returns the only index of its argument. In the second, all the elements are the same, so the first element is returned.

Sign up to request clarification or add additional context in comments.

Comments

0
x = [[1,2,3],[4,5,6],[7,8,9]]

for i in x:
# i = [1,2,3] -> index of [1,2,3] in x should be 0
# i = [4,5,6] -> index of [4,5,6] in x should be 1 because x[0] is not equal to [1,2,3]
# i = [1,2,3] -> index of [1,2,3] in x should be 2 because not x[0] nor x[1] is equal to i.
   print(x.index(i))

y = [['X' for x in range(3)] for x in range(3)]
# so y = [['X', 'X', 'X'], ['X', 'X', 'X'], ['X', 'X', 'X']]
for i in y:
# i = ['X','X','X'] -> index of ['X','X','X'] in x should be 0
# i = ['X','X','X'] -> index of ['X','X','X'] in x should be also 0
# i = ['X','X','X'] -> index of ['X','X','X'] in x should be one more time 0

The problem is that function x.index(i) finds the first index which is equal to the value you described. Python cannot see that you have already got index 0, so after second for loop threw i in y it takes index 0 and will always take that value because the value of i which is always equal to i = ['X', 'X', 'X'] is x[0] = ['X', 'X', 'X'] and x[0] is the first index equal to i.

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.