Python has built-in
functions for picking item(s) randomly from a sequence.
Single
For a single item you can use choice
:
# select.py
from random import choice
fellowship = (
"Mithrandir",
"Frodo",
"Legolas",
"Aragorn",
"Gimli",
"Sam",
"Boromir",
"Pippin",
"Merry",
)
def main():
selection = choice(fellowship)
print(f"selection: {selection}")
if __name__ == "__main__":
main()
Output:
selection: Mithrandir
Multiple
For multiple selections you can use choices
or sample
:
# select.py
from random import choices, sample
fellowship = (
"Mithrandir",
"Frodo",
"Legolas",
"Aragorn",
"Gimli",
"Sam",
"Boromir",
"Pippin",
"Merry",
)
def main():
selection = choices(fellowship, k=3)
print(f"selection: {selection}")
selection = sample(fellowship, k=3)
print(f"selection: {selection}")
if __name__ == "__main__":
main()
Output:
selection: ['Gimli', 'Merry', 'Pippin']
selection: ['Boromir', 'Aragorn', 'Legolas']
For more info look at: python - random for sequences
All done!
Top comments (0)