Picking a Random Word from a list in python?

Question:

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

Asked By: Noah R

||

Answers:

Use the random.choice() function:

>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks
Answered By: Greg Hewgill
>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'
Answered By: jtdubs
str='book pen paper pencil'
x=str.split()
print(x)
import random
print(random.choice(x))
Answered By: Ravikiran D
str='book pen paper pencil'
x=str.split()
print(x)
y=len(x)
import random
z=random.randrange(-1,y)
print(x[z])
Answered By: Ravikiran D
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.