How to generate a random item from a list several times in a row, but everytime it´s a different item generated

Viewed 512

I have a list :

x = ["A","B","C"]

and I want to print out a random item a random number of times but every time the random item is generated it should be different for example:

ACBAACBB

what is the simplest way to do that?

2 Answers

This essentially requires two elements of the random package, one to generate a random element from the list x, and the other to generate a random number which would act as the length of the desired output.

import random
x = ["A","B","C"]
r = random.randint(1,100)
st = ''
for i in range(r):
    var = random.choice(x)
    st += var
print (st)

This generates outputs ranging from 1 to 100 in length. Modify the random.randint(1,100) to get the desired output length.

You can set limits on the length of the string manually, and then choose a random element from the list each time you want a new character using iteration.

The following code will print a string in this format with a minimum range of 1 and a maximum range of 10

import random

x = ["A","B","C"]

text = ""

for i in range(random.randint(1,10)):
    text += random.choice(x)

print(text)
Related