how to stop a for loop

Viewed 315833

I'm writing a code to determine if every element in my nxn list is the same. i.e. [[0,0],[0,0]] returns true but [[0,1],[0,0]] will return false. I was thinking of writing a code that stops immediately when it finds an element that is not the same as the first element. i.e:

n=L[0][0]
m=len(A)
for i in range(m):
 for j in range(m):
   if
    L[i][j]==n: -continue the loop-
   else: -stop the loop-

I would like to stop this loop if L[i][j]!==n and return false. otherwise return true. How would I go about implementing this?

9 Answers

I know this question was asked a long time ago, but if that could help anyone else, here's my answer:

I find it easier to understand with the use of a while loop and it will stop both for loops that way. The code below also return the True/False as asked when the function check_nxn_list() is called. Some parameters may have to be added in the function call.

def check_nxn_list():
    state = True
    n=L[0][0]
    m=len(A)
    while state == True:
        for i in range(m):
            for j in range(m):
                if L[i][j]!=n:
                    state = False
        break
    return state

The break at the end of the while loop is required to end the loop even if state stays True.

To stop your loop you can use break with label. It will stop your loop for sure. Code is written in Java but aproach is the same for the all languages.

public void exitFromTheLoop() {
    boolean value = true;
            loop_label:for (int i = 0; i < 10; i++) {
              if(!value) { 
                 System.out.println("iteration: " + i);
              break loop_label;
        }
    }
}   

}

Related