Irkl1_
Irkl1_

Reputation: 71

How to get variable out of a nested loop?

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

Upvotes: 0

Views: 923

Answers (2)

peter
peter

Reputation: 786

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()

Upvotes: 1

Vedhas Deshpande
Vedhas Deshpande

Reputation: 66

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))

Upvotes: 1

Related Questions