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

Issue

This Content is from Stack Overflow. Question asked by William Humpsburg the 7th

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:
            print(...)



Solution

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)


This Question was asked in StackOverflow by William Humpsburg the 7th and Answered by Michael M. It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?