'Find the string that was NOT chosen in python
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
Solution 1:[1]
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
Solution 2:[2]
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)
Solution 3:[3]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sytech |
| Solution 2 | |
| Solution 3 | Ned Hulton |
