Calvin Shadle
Calvin Shadle

Reputation: 13

Selecting a Random list?

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

Answers (2)

Jahnavi Sananse
Jahnavi Sananse

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

AKX
AKX

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

Related Questions