'Why is break statement not working in this situation (python)? [duplicate]

I have two lists:

list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]

and I want to add List2 to List1 until we find the first sum that is larger than 10, print out the summation, and stops.

My code is:

for val1 in list1: 
   for val2 in list2:
      if val1+val2 > 10 :
        print (val1, val2, val1 + val2)
        break
      else:
        continue

But the result is:

0 11 11
1 10 11
2 9 11
3 8 11
4 7 11
5 6 11

How to make the loop stops at the first sum? many thanks. Note: I want to maintain the for...if loop structure.



Solution 1:[1]

Your 'break' statement only breaks out of the first (EDIT: innermost) loop. Put it into a function and return a value like so:

def foo(list1, list2):
    for val1 in list1: 
        for val2 in list2:
            if val1+val2 > 10 :
                print (val1, val2, val1 + val2)
                return (val1 + val2) # or whatever you are interested in
            else:
                continue

Solution 2:[2]

break keyword is used to break out of only one loop to break out of multiple loop use _break boolean variable initially which is False

list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]

_break = False

for val1 in list1: 
   for val2 in list2:
      if val1+val2 > 10 :
        print (val1, val2, val1 + val2)
        _break = True
        if _break:
         break
   if _break:
       break

Output:

0 11 11

Solution 3:[3]

Just maintain a flag variable to break out of the outer loop.

list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
flag=0
for val1 in list1: 
    for val2 in list2:
        if val1+val2 > 10 :
            print (val1, val2, val1 + val2)
            flag=1
            break
        else:
            continue
    if(flag):
        break

If you don't have anything to execute after this, you can use exit() method to terminate the code.

list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
for val1 in list1: 
    for val2 in list2:
        if val1+val2 > 10 :
            print (val1, val2, val1 + val2)
            exit()
        else:
            continue

Solution 4:[4]

It's just breaking the inner loop. If you want break both for loop then, You can use flag.

list1 = [0,1,2,3,4,5]
list2 = [6,7,8,9,10,11]
flag = 0
for val1 in list1: 
    for val2 in list2:
        if val1+val2 > 10 :
            print(val1, val2, val1 + val2)
            flag = 1
            break
        else:
            continue
     if flag:
         break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Udesh Ranjan
Solution 3 Ponprabhakar S
Solution 4 Mayur Dhamecha