How to print a random choice many times in one line in python

94 views Asked by At

I'm trying to print a custom amount of random choices in one line looping a "print(random.choice(list)", but the problem comes when looping it with a "for" loop or something similar won't print the choices in the same line, and if I try multiplying "print(random.choice(list)" by an amount of times (or doing something similar) would print that amount of times the same random choice.

these are the options I've tried

list = ("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g"), ("h"), ("i"), ("j")

print(random.choice(list) * 10)

that would output something like this: aaaaaaaaaa, bbbbbbbbbb, cccccccccc...

the only way to output some random choices in one line that I've found out is this:

print(random.choice(list), random.choice(list), random.choice(list), random.choice(list), random.choice(list))

that would output something like this: i d f i d

and beside that not being pretty and poorly coded, that's the output I'm looking for

4

There are 4 answers

0
Andrej Kesely On

You can use random.choices() with k=10 parameter to get 10 characters from the population (list/string) with replacement:

import random

s = "abcdefghij"

print(*random.choices(s, k=10))

Prints for example:

i d a f e e d h g a
0
Barmar On

You're only calling random.choice(list) once, and multiplying that.

You can use a generator expression to call it multiple times.

mylist = ("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g"), ("h"), ("i"), ("j")

print(*(random.choice(mylist) for _ in range(10)))
0
Jiří Baum On

As @AndrejKesely already answered, in this case, there's a special function for that:

options = ("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g"), ("h"), ("i"), ("j")

print(*random.choices(options, k=10))

More generally, if there isn't a function, you could use a comprehension:

options = ("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g"), ("h"), ("i"), ("j")

print(*(random.choice(options) for _ in range(10)))

Comprehensions are generally quite useful; they let you take a sequence (in this case, the integers 0..9) and transform it (in this case, ignore the integer and choose an option at random).

As a side-note, it's good style to avoid using the variable name list, since that's also a built-in type; better to use a different name to avoid confusion.

0
Gokay Gok On

The join method is used to concatenate the random choices into a single string, separated by spaces.

list = ("a"), ("b"), ("c"), ("d"), ("e"), ("f"), ("g"), ("h"), ("i"), ("j")
amount_of_choices = 5 

print(" ".join(random.choice(my_list) for _ in range(amount_of_choices)))