Dean Arvin
Dean Arvin

Reputation: 115

Print random strings from a list (multiple times) with no repeats

I want to print random strings from the same list multiple times throughout the program, but without repeating any of the previously printed random strings.

If I had the following:

core = 'a', 'b', 'c', 'd'

print (random.sample(core[0:], k=2))
print (random.sample(core[0:], k=2))

I'd like the outcome to look something like:

b, d
c, a

Upvotes: 3

Views: 603

Answers (2)

Austin
Austin

Reputation: 26039

random.sample itself works without replacement, so there is no case of repetition. Get a sample of 4 and slice:

randoms = random.sample(core, 4)

print(randoms[:2])
print(randoms[2:])

Upvotes: 6

kuro
kuro

Reputation: 3226

You can use shuffle() from random. Then use slicing to extract necessary elements.

import random

initial = 'a', 'b', 'c', 'd'
l = list(initial)
random.shuffle(l)

print (l[:2])
print (l[2:])

Output:

['a', 'c']
['b', 'd']

Upvotes: 1

Related Questions