0

My question is very simple how can I get the result variable out of this nested loop:

for row in new_matrix:
    for col in row:
        if col == 'S':
            result = [(new_matrix.index(row), row.index(col))]

I tried assigning a global variable result above and set it equal to this expression [(new_matrix.index(row), row.index(col))] but it didn't work, I want to do it without using global because it's bad practice

5
  • 1
    return it from a function. Commented Apr 7, 2021 at 21:29
  • if you do not want to look further,just use break to finish the loop Commented Apr 7, 2021 at 21:29
  • @JurajBezručka can't break a nested loop. Commented Apr 7, 2021 at 21:30
  • Also your second for loop is not properly indented. Commented Apr 7, 2021 at 21:35
  • Assigning a default value to a variable and then changing it inside a a (nested) loop is not what is meant about avoiding global variables — which are variables defined outside of a function or method whose values get changed inside one. Here's more information. In other words, your code is basically fine except for assigning an initial value to the variable before entering the loops which in your case that didn't work because row and col are only defined inside them. The fix is to simply use None instead. Commented Apr 7, 2021 at 22:25

2 Answers 2

1

Lists are mutable in python, so you can do this way:

result = []
for row in new_matrix:
   for col in row:
      if col == 'S':
         result.append(new_matrix.index(row), row.index(col))
Sign up to request clarification or add additional context in comments.

Comments

1
def your_function():
    for row in new_matrix:
        for col in row:
            if col == 'S':
                return [(new_matrix.index(row), row.index(col))]

result = your_function()

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.