Search code examples
pythonlistfor-loopif-statementbreak

Using a for if break statement to append values in a list


I'm working with loops and I got a question, so I have a simple for loop that append random values between 0 and 1, basically what I need is to keep adding values until a certain number of 0 or 1 appear, for example:

iteration 1 = [0]
iteration 2 = [0,1]
...
iteration 6 = [0,1,1,1,1,1] #Here appear five 1's so I break the loop (it can be another number not necessarily 5 ones or 5 zeros)

The for loop is pretty simple:

import numpy as np

value = []
for i in range(5):
    value.append(np.random.randint(0, 2))
    print(value)

And here is what I tried to break the loop using a if-break statement

value = []
for i in range(5):
    if value == value:
        value.append(np.random.randint(0, 2))
    else
        break

    print(value) 

My biggest problem is that I don't know how to specify the codition that if a certain numbers of 0 or 1 appears break the loop, so I was hoping you can point me to a right direction. Thank you in advance!


Solution

  • In such scenarios when you don't know exactly how many number of iterations are required, using while loop is the defacto standard You can have two variables as maximum allowed numbers, for this example I'm using numOnes as 5 and numbZeros as 3, use While True loop and check for condition at each iteration then break if the condition doesn't satisfy.

    import numpy as np
    numOnes = 5
    numZeros = 3
    value = []
    while True:
        value.append(np.random.randint(0, 2))
        print(value)
        if value.count(0) >= numZeros or value.count(1)>=numOnes:
            break
    

    Since you typically asked about break statement, so I used if condition, otherwise you can just have the condition with while loop itself like while value.count(0) >= numZeros or value.count(1)>=numOnes:

    Also, if you are using for loop because you want only specified number of iterations, then your loop is fine and you don't need to use while loop, just add the if condition at the exit point of loop:

    import numpy as np
    numOnes = 5
    numZeros = 3
    value = []
    for i in range(5):
        value.append(np.random.randint(0, 2))
        print(value)
        if value.count(0) >= numZeros or value.count(1)>=numOnes:
            break