In Python 3, how would I print a random word from a list of words?
Python random.choice() function The choice() function of a random module returns a random element from the non-empty sequence. For example, we can use it to select a random password from a list of words. Here sequence can be a list, string, or tuple.
The simplest way to use Python to select a single random element from a list in Python is to use the random. choice() function. The function takes a single parameter – a sequence. In this case, our sequence will be a list, though we could also use a tuple.
Python's random module provides a sample() function for random sampling, randomly picking more than one element from the list without repeating elements. It returns a list of unique items chosen randomly from the list, sequence, or set. We call it random sampling without replacement.
Use the random.choice()
function:
>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks
>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With