Q:

how to keep on executing this code until the last element comes "4" in the output list

When I execute the code below, I'm getting 
[0,0,1,2,2,3,4,4,5,6,7]
However, I expect this: 
[0,0,1,1,2,2,2,2,3,3,4] 
I expect that output because print should only happen until the last element of list (tails[-1]) is equal to 4. 
import numpy as np
np.random.seed()
tails = [0]
for x in range(10):
    coin = np.random.randint(0, 2)
    tails.append(tails[x] + coin)
    if tails[-1] == 4:
        print(tails)

A:

Try break keyword after printing last element in tails if it is 4.
if tails[-1] == 4:
    print(tails)
    break

and then may be try exiting the script using sys.exit().

