This will create an iterator that always starts with 1, it will then randomly choose if it's a 0 or 1, once it is a 0 it will always be 0 until a new version is called.
Shortened version
import random def on_till_randomly_off(count): if not count: return current_count = 0 while True: if current_count == count: return yield 1 current_count += 1 if random.randint(0, 1): break while True: if current_count == count: return yield 0 current_count += 1 print("-".join(str(state) for state in on_till_randomly_off(5))) print("-".join(str(state) for state in on_till_randomly_off(5))) print("-".join(str(state) for state in on_till_randomly_off(5))) print("-".join(str(state) for state in on_till_randomly_off(5))) print("-".join(str(state) for state in on_till_randomly_off(5)))
Output:1-0-0-0-0
1-1-1-0-0
1-0-0-0-0
1-1-1-1-1
1-0-0-0-0
Shortened version
def on_till_randomly_off2(count): state = 1 for _ in range(count): yield state if state: state = random.randint(0, 1)