Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random item every time a key is pressed?

Tags:

python-3.x

My program should get a random name from a list every time a key is pressed, and then delete that name from the list. With the code I have now a random name is selected, but the list is emptied completely.

I have tried both a for and a while loop, but I'm uncertain as what to use in this situation.

x = win.getKey()
while len(members) > 0:
    if x:
        name = random.choice(members)
        members.remove(name)

As mentioned above I want to draw a random name and delete that name from the list every time a key is pressed, until the list is empty.

like image 852
LDR Avatar asked Dec 06 '25 03:12

LDR


1 Answers

You'll need to put your key prompt in the loop to cause the loop to pause and wait for input for each element, otherwise the loop will run to completion and instantly empty the entire list.

import random

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

while members:
    if win.getKey():
        choice = random.choice(members)
        members.remove(choice)
        print(choice)

Output:

8
4
2
3
7
6
9
5
1

If the list is very large, remove is a slow linear operation that needs to inspect each element in the list one by one to find a match. Consider using a fast (amortized) constant time pop operation which uses an index to find the target element without searching:

import random

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

while members:
    if win.getKey():
        choice = members.pop(random.randint(0, len(members) - 1))
        print(choice)
like image 66
ggorlen Avatar answered Dec 12 '25 10:12

ggorlen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!