5

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?

1
  • 6
    How about concatenating the lists i.e.:num = random.choice(list_1 + list_2) Commented Nov 24, 2018 at 16:24

3 Answers 3

3

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]))
Sign up to request clarification or add additional context in comments.

2 Comments

In python3 you can use it too: num = random.choice([*list_1, *list_2])
yes, i'm running python 3.7 and it seems to work @MiklosHorvath
-1

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

Comments

-1

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']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.