DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Random Select for Sequences in Python

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()
Enter fullscreen mode Exit fullscreen mode

Output:

selection: Mithrandir
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

Output:

selection: ['Gimli', 'Merry', 'Pippin']
selection: ['Boromir', 'Aragorn', 'Legolas']
Enter fullscreen mode Exit fullscreen mode

For more info look at: python - random for sequences

All done!

Top comments (0)