Python: If an item in list A exists in list B then output a random result that is not the same


Basically, I have 2 lists like this:

list_A = [A,B,C,D,E]
list_B = [B,C,A,E,D]

and I want to output one random element from each list:

Example Output:

From list_A: "A"
From list_B: "D"

How do I write code to avoid giving the same element?

Example of wrong output:

From list_A: "A"
From list_B: "A"

This is what I tried but don’t know how to continue:

for a in list_A:
    for b in list_B:
        if a in list_B:


You can do this:

import random

list_A = ['A', 'B', 'C', 'D', 'E']
list_B = ['B', 'C', 'A', 'E', 'D']

a = random.choice(list_A)
b = random.choice(list_B)
while a == b:
  b = random.choice(list_B)

print('From list_A: ' + a)
print('From list_B: ' + b)
Answered By: Michael M.

I am sure there are better ways of doing this, but I think this is the simplest one to understand:

import random
list_a = ["A", "B", "C", "D", "E"]
list_b = ["A", "F", "G", "H", "I"]
rand_a = random.choice(list_a)
rand_b = random.choice(list_b)
while(rand_a == rand_b):
    rand_b = random.choice(list_b)
Answered By: Varad Karpe

From my point of view the best way of doing it is as follows:

import random
from itertools import permutations
list_AB = ['A','B','C','D','E']
pairsAB = list(permutations(list_AB, 2))
print( random.choice(pairsAB) )

The above solution is valid in the above case of question as lists A and B have same elements so random choice from one is equivalent to random choice from the other. This allows to create all possible pairs of results and then choose random from them.

Another sub-optimal approach to the same requirement is using sets:

list_A = ['A','B','C','D','E']
list_B = ['B','C','A','E','D']
set_B = set(list_B)
import random
choice_A = random.choice(list_A)
choice_B = random.choice(list(set_B-set(choice_A)))
print( choice_A, choice_B )

The approach above does not unnecessary loop choosing always only twice and doesn’t also need any if statement or or == comparison. There is a good reason why Python provides sets along with lists and dictionaries.

Answered By: Claudio

You can do like this,

list_A = ['A', 'B', 'C', 'D', 'E']
list_B = ['B', 'C', 'A', 'E', 'D']

a = random.choice(list_A)
b = random.choice([i for i in list_B if i != a])

print(f'From list_A: {a}')
print(f'From list_B: {b}')

# Result
From list_A:A
From list_B:C
Answered By: Rahul K P
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.