Ben
Ben

Reputation: 39

Print different strings from a sequence multiple times using tuple

I want to print from a sequence randomly and print a different choice each time Example:

import random
word = ("Python", "Apple", "Mountain", "Star Trek")
correct = random.choice(word)
print(correct * 3) # I'll get a single random choice printed three times 

#or 
for i in range 3:
   print(correct)
# I'll have again a single random choice printed three times.

What I want instead is to print three different choices with a single print command.

Upvotes: 0

Views: 80

Answers (2)

Lapis Rose
Lapis Rose

Reputation: 644

You can make 3 choices using random.choices(list, k=# of choices) and then print them out. This will give you 3 random words with replacement.

import random 
word = ("Python", "Apple", "Mountain", "Star Trek") 
choices = random.choices(word, k=3) 
for choice in choices:
    print(choice)

If you want 3 random words without replacement, consider using random.sample(list, # of choices).

import random 
word = ("Python", "Apple", "Mountain", "Star Trek") 
choices = random.sample(word, 3) 
for choice in choices:
    print(choice)

Upvotes: 2

Michael Bianconi
Michael Bianconi

Reputation: 5242

Choose randomly from the list, remove it, print it, and repeat twice.

import random

def print3(items):
    for i in range(0, 3):
        item = random.choice(items)
        items.remove(item)
        print(item)

print3(['a','b','c','d','e','f'])

Upvotes: 0

Related Questions