Home > Back-end >  Find the string that was NOT chosen in python
Find the string that was NOT chosen in python

Time:04-01

I am trying to choose a random string from a list, then create a variable with the string that was not chosen.

import random

gamers = ["bob", "joe"]
winner = random.choice(gamers)
loser = #? what do I do now to get the loser

CodePudding user response:

If you only have two elements in the list, you can use random.shuffle instead and just extract the two elements:

gamers = ["bob", "joe"]
random.shuffle(gamers)
winner, loser = gamers

CodePudding user response:

Instead of random.choice, you could use random.sample and assign the loser together with the winner (credit to @Kraigolas for recognizing my previous error; thanks):

winner, loser = random.sample(gamers, k=2)

CodePudding user response:

import random

gamers = ["bob", "joe"]
winner = random.choice(gamers)
print(winner)
gamers.remove(winner)

for loser in gamers:
        print(loser   " is a loser")

You can remove the winner with this gamers.remove(winner)

  • Related