Noah R
Noah R

Reputation: 5477

Picking a Random Word from a list in python?

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

Upvotes: 20

Views: 121194

Answers (4)

Ravikiran D
Ravikiran D

Reputation: 339

str='book pen paper pencil'
x=str.split()
print(x)
y=len(x)
import random
z=random.randrange(-1,y)
print(x[z])

Upvotes: 3

Ravikiran D
Ravikiran D

Reputation: 339

str='book pen paper pencil'
x=str.split()
print(x)
import random
print(random.choice(x))

Upvotes: 3

jtdubs
jtdubs

Reputation: 13963

>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'

Upvotes: 6

Greg Hewgill
Greg Hewgill

Reputation: 992697

Use the random.choice() function:

>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks

Upvotes: 35

Related Questions