The Python Oracle

how to stop a for loop

This video explains
how to stop a for loop

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 Question
00:44 Accepted answer (Score 98)
01:14 Answer 2 (Score 63)
02:52 Answer 3 (Score 4)
03:15 Answer 4 (Score 0)
03:30 Thank you

--

Full question
https://stackoverflow.com/questions/6346...

Answer 2 links:
[break]: http://docs.python.org/tutorial/controlf...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 119


Use break and continue to do this. Breaking nested loops can be done in Python using the following:

for a in range(...):
   for b in range(..):
      if some condition:
         # break the inner loop
         break
   else:
      # will be called if the previous loop did not end with a `break` 
      continue
   # but here we end up right after breaking the inner loop, so we can
   # simply break the outer loop as well
   break

Another way is to wrap everything in a function and use return to escape from the loop.




ANSWER 2

Score 5


Try to simply use break statement.

Also you can use the following code as an example:

a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]

def check_matr(matr, expVal):    
    for row in matr:
        if len(set(row)) > 1 or set(row).pop() != expVal:
            print 'Wrong'
            break# or return
        else:
            print 'ok'
    else:
        print 'empty'
check_matr(a, 0)
check_matr(b, 0)



ANSWER 3

Score 0


Use the break statement: http://docs.python.org/reference/simple_stmts.html#break




ANSWER 4

Score 0


Others ways to do the same is:

el = L[0][0]
m=len(L)

print L == [[el]*m]*m

Or:

first_el = L[0][0]
print all(el == first_el for inner_list in L for el in inner_list)