In Python 3, how would I print a random word from a list of words?
Asked
Active
Viewed 1.1e+01k times
4 Answers
34
Use the random.choice()
function:
>>> import random
>>> a = ["Stack", "Overflow", "rocks"]
>>> print(random.choice(a))
rocks

Greg Hewgill
- 951,095
- 183
- 1,149
- 1,285
6
>>> import random
>>> random.choice("hello world".split())
'hello'
>>> random.choice("hello world".split())
'world'

jtdubs
- 13,585
- 1
- 17
- 12
-
3Did you actually run it until you got this output? Or did you fake it =P – Falmarri Dec 09 '10 at 01:54
-
-
-
-
The fact that the first word was "hello" doesn't affect the 50/50 chances of second one being "world" does it? – martineau Dec 09 '10 at 03:16
-
3No, @martineau, it doesn't. It was a 50% chance of the first one being 'hello', and a 50% chance of the second being 'world'. .5 * .5 = .25. – JasonFruit Dec 12 '10 at 18:13
-
OK, I get it...but I'm not sure what the big deal is about the output happening to be "hello" followed by "world" since the probability of that is exactly the same as it being any other combination (even if it's less than 50/50). – martineau Dec 12 '10 at 20:57
3
str='book pen paper pencil'
x=str.split()
print(x)
import random
print(random.choice(x))

legoscia
- 39,593
- 22
- 116
- 167

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

AChampion
- 29,683
- 4
- 59
- 75

Ravikiran D
- 329
- 3
- 8
-
1
-
its a logic without using any random sequences. any way@AChampion thank you for editing my code. – Ravikiran D Jul 06 '17 at 16:45