Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking a Random Word from a list in python?

In Python 3, how would I print a random word from a list of words?

like image 502
Noah R Avatar asked Dec 09 '10 01:12

Noah R


People also ask

How do you select a random word from a list in Python?

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.

How do you pull a random item from a list in Python?

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.

How do you select random names from a list without repetition in Python?

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.


2 Answers

Use the random.choice() function:

>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks
like image 167
Greg Hewgill Avatar answered Sep 19 '22 15:09

Greg Hewgill


>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'
like image 21
jtdubs Avatar answered Sep 20 '22 15:09

jtdubs