2

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?

1
  • random.choice(x) Commented May 10, 2020 at 17:54

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it works better than what the OP provided.
1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.