Reputation: 13
So I have 3 lists:
a = []
b = ["a", "b", "c"]
c = ["d", "e", "f"]
how can I randomly select either list b or c and import it into list a?
Thanks.
Upvotes: 0
Views: 96
Reputation: 118
To get random elements from sequence objects such as lists (list
), tuples (tuple
), strings (str
) in Python, use choice()
, sample()
, choices()
of the random
module.
The choice()
method returns one random element, and the sample()
and choices()
methods return a list of multiple random elements. The sample()
is used for random sampling without replacement, and choices()
is used for random sampling with replacement.
The random
method — Generate random numbers.
import random
l = [0, 1, 2, 3, 4]
print(random.choice(l))
Upvotes: 2
Reputation: 169032
Use random.choice
:
import random
a = ['foo']
b = ['bar', 'quux']
c = ['spam', 'eggs']
a.extend(random.choice([b, c]))
a
will end up being either ['foo', 'bar', 'quux']
or ['foo', 'spam', 'eggs']
.
Upvotes: 5