Yasuo God
Yasuo God

Reputation: 51

Random Elements from two Lists - Python

So I have two lists in Python:

import random
list_1 = ['1','2','3']
list_2 = ['4','5','6']
num = random.choice(list_1 or list_2)

This doesn't seem to work. How can I get a random number from either list 1 or list 2?

Upvotes: 5

Views: 3761

Answers (3)

use random.sample to select from the two lists. If you want to select exclusively from one list or another you can use a mod % and flip even and odd where one list is even and one list is odd then randomly sample.

name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','woman','shopping','pen','mouse']

result=[]
for i in range(10):
    a=random.sample(name,1)
    b=random.sample(second,1)
    result.append(a[0]+ b[0])
print(result)
#[result.append(random.sample(name,1)[0]+random.sample(second,1)[0]) for i in 
range(10)]
print(result)

output:

 ['I buy pen', 'I buy cat', 'I like woman', 'I have water', 'I hate water', 'I want water', 'I buy water', 'I see banana', 'I love woman', 'I buy woman']

randomly flipping between two lists

result=[]
for i in range(10):
    a_num=random.sample(range(10000),1)
    if a_num[0]%2:
        result.append(random.sample(name,1))
    else:
        result.append(random.sample(second,1))
print(result)

output:

[['mouse'], ['I see '], ['banana'], ['cat'], ['I buy '], ['soap'], ['woman'], ['I like '], ['soap'], ['cat']]

Upvotes: -1

Mark K
Mark K

Reputation: 9338

Not short but could be a reference...

import random

name = ['I love ','I have ','I hate ','I want ','I buy ','I like ','I see ']
second = ['banana','lemon','water','cat','soap','man','shopping','pen','mouse']

population = list(zip(name, second))
ox_list = []

for a in range(20):
    samples = random.sample(population, 1)
    samples = str(samples).strip('[]')
    ox_list.append(samples.replace("', '", ''))

for o in set(ox_list):
    print (o.replace("')",'').replace("('",''))

I have lemon
I want cat
I love banana
I like man
I buy soap
I hate water
I see shopping

Upvotes: -1

prophet-five
prophet-five

Reputation: 559

You can concatenate the lists:

num = random.choice(list_1 + list_2)

or alternatively choose a list and then choose a character:

num = random.choice(random.choice([list_1],[list_2]))

Upvotes: 3

Related Questions