How do I count shared elements between 2 different lists? (Python)

Viewed 77

I'm trying to have the program count how many elements in 2 different lists are shared.

One list is randomized.

import random

Lotterya = [random.randint(1,49) for _ in range(6)]

And the other is user-input.

Lotteryb = []
while len(Lotteryb) < 6:
    n = int(input("enter number: "))
    Lotteryb.append(n)

What code do I use to let the program say: "There are _ numbers in common."?

2 Answers

Convert both to set and take intersection

x = set(Lotterya)
y = set(Lotteryb)

z = x.intersection(y)

print(z)

Converting the two lists into sets and the finding the intersection to fin the common elements. As shown below:-

list1 = [1, 2, 3, 2, 3, 2, 1, 1, 1]
list2 = [1, 4, 3, 5, 2, 7, 8, 2, 1]

set1 = set(list1)
set2 = set(list2)

result = set1.intersection(set2)
print(result)  # elements that are common
print(len(result))  # number of elements that are common

This might help.

Related