Skip to content
Advertisement

Random list item, but unable to choose the same item twice

Is it possible to run a loop, that chooses a random list item, but is unable to choose the same one twice in a row. I’ve tried running it in a thread and with Clock.schedule_interval Im not sure how to keep the loop and GUI running simultaneously. When the interval goes off, it “resets” the loop. therefore being able to choose the same item again.

def toggle(self):
    self.start()
    i = self.root.ids.interval.text #interval
    i = int(i)
    Clock.schedule_interval(self.playsound, i)

def playsound(self, *args):
    while True:
        sounds = [1,2,3,4]
        t = random.randrange(len(sounds)-1)
        sounds.append(sounds.pop(t))         
        x = (sounds[-1])     
        if x == 1:
            print("1")
        elif x == 2:
            print("2")
        elif x == 3:
            print("3")
        elif x == 4:
            print("4")

Advertisement

Answer

You should initialize sounds before the loop:

def playsound():
    sounds = [1,2,3,4]
    while True:
        t = random.randrange(len(sounds)-1)
        ...
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement