Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How to use random to get two numbers in different orders

I am looking for a fast way to get 2 integers randomly say 1, 2 or 2, 1.

    var1 = random.randint( 1, 2 )
    # do something
    var2 = random.???       # say if var1 == 1, var2 should be 2.
    # do something else

Is there something that can be done to achieve following (Some other syntactical way)

    var2 = ( 1, 2 ) - var1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Many solutions are possible, but the one which matches your idea most would be to use a compact if else statement:

import random

var1 = random.randint(1, 2)
var2 = 2 if var1 == 1 else 1

Another easy way to go is to create a list of values and shuffle them:

import random

l = list(range(1, 3))
random.shuffle(l)
var1 = l[1]
var2 = l[2]

Or use an in build function of random directly sovling your issue:

import random

var1, var2 = random.sample([1, 2], k=2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading