Yeo Sze Ping
Yeo Sze Ping

Reputation: 23

How to print a random value name from a list?(python)

Let's say:

list=["A","B","C"]
listitem = random.randint(0,2)

I typed:

print listitem

but it gives a number and I'd like a letter?

How can I do this?

Upvotes: 2

Views: 187

Answers (2)

bryce
bryce

Reputation: 488

You need to use the random index to reference the item in your list.

>>> import random
>>> list=["A","B","C"]
>>> listitem = random.randint(0,len(list))
>>> list[listitem]
'A'
>>> listitem = random.randint(0,len(list))
>>> list[listitem]
'B'

Or, if you don't care about the index, just select an item at random using the random.choice() routine:

>>> random.choice(list)
'B'
>>> random.choice(list)
'B'
>>> random.choice(list)
'A'
>>> random.choice(list)
'C'

Upvotes: 1

Zulu
Zulu

Reputation: 9275


You can use random :

 >>> from random import choice
 >>> List = [ 'A','B','C' ]
 >>> choice( List )
 C
 >>> choice( List )
 A
 >>> choice( List )
 B

Upvotes: 3

Related Questions