0

I want the loop to break if True occurs. For some reason, the break statement get things twisted.

a = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [7,5,3]]
b = [[9], [9, 7], [9, 7, 8], [9, 7, 8, 2]]

countdata = []

for x in range(len(b)):
    for y in range(len(a)):
        if all(elem in b[x] for elem in a[y]) == True: 
            break      
        countdata.append(all(elem in b[x] for elem in a[y])) 

print(len(countdata))

Output:

>>>20

The output should be 18. Proof:

countdata = []

for x in range(len(b)):
    for y in range(len(a)):
        tt = all(elem in b[x] for elem in a[y] )
    
        countdata.append(tt)

nylista = []


for z in countdata:
    if z == True:
        break
    nylista.append(z)

print(len(nylista))

>>>18

Is it a bug?

Emily
  • 1
  • 1
  • Given your code, the output is `1`. – BcK Mar 17 '21 at 11:56
  • 1
    I didn't look into your code, but this might be related: https://stackoverflow.com/questions/653509/breaking-out-of-nested-loops Note that `break` only escapes the inner-most for loop. – lukover Mar 17 '21 at 12:00

3 Answers3

1

You're breaking the inner loop, but not the outer loop, so the outer loop continues, and then runs the inner loop again (which itself breaks when [7, 8, 9] is contained in [9, 7, 8, 2]).

There are a number of solutions for breaking multiple loops for you to look at.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

As stated here you are not breaking out of the external loop:

a = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [7,5,3]]
b = [[9], [9, 7], [9, 7, 8], [9, 7, 8, 2]]



countdata = []
inner_break = False
for x in range(len(b)):
    if inner_break:
        break
    for y in range(len(a)):
        if all(elem in b[x] for elem in a[y]) == True:
            inner_break = True
            break
        countdata.append(all(elem in b[x] for elem in a[y]))

print(len(countdata))
David Meu
  • 1,527
  • 9
  • 14
0

First, corrections in your code segment. The code segment you intend is

countdata = [] 

for x in range(len(b)): 
    for y in range(len(a)): 
        if all(elem in b[x] for elem in a[y]) == True:  
            break       
        countdata.append(all(elem in b[x] for elem in a[y]))

Next, when you encounter the break statement you are exiting the inner loop only. Hence the difference in answers.

countdata = [] 
in_flag = False

for x in range(len(b)): 
    for y in range(len(a)): 
        if all(elem in b[x] for elem in a[y]) == True:  
            in_flag = True
            break       
        countdata.append(all(elem in b[x] for elem in a[y]))
    if in_flag:
        break

This should fix it.

DeGo
  • 783
  • 6
  • 14