2

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?

2 Answers 2

3


You can use random :

 >>> from random import choice
 >>> List = [ 'A','B','C' ]
 >>> choice( List )
 C
 >>> choice( List )
 A
 >>> choice( List )
 B
Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.