2

I am attempting to reassign variables inside nested for loops. I'd like to get the index for the number 6 inside a list of lists, but it's not working. Why isn't it working and how can I fix it?

Here's the code:

row = 0
col = 0
a = [[1, 2, 3, 4, 5], [3, 4, 4, 6, 9]]
for i in range(len(a)):
  for j in range(len(a)):
    if a[i][j] == 6:
      row = i # expect row = 1
      col = j # expect col = 3
print(row) # prints 0
print(col) # prints 0

2 Answers 2

4

row and col are not updated because the if statement is never executed. The loop with the j variable needs to be based on the length of a[i], not a, as a has a length of two while the lists inside it each have a length of 5. With that restriction, it's not finding the 6 element.

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

Comments

1

Your second line should iterate over the second dimension, so

  for j in range(len(a[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.