• Register
1 vote
47 views

Problem:

I was trying to find common elements in two lists python. So I wrote this code:
x = [1, 2, 6, 9]
y = [1, 3, 8, 9]


x_as_set = set(y)
intersection =x_as_set.intersection(y)


intersection_as_list = list(intersection)

print(intersection_as_list)

But when I compile this it gives error. Please help me to find common elements in two lists python

6.1k points

Please log in or register to answer this question.

1 Answer

1 vote

Answer:

Main error of your code is caused by the line:

x_as_set = set(y)

If you put a list of ain a list of b it will not compare but it will take each of its elements to show.

So your code should be like:

 

x = [1, 2, 6, 9]
y = [1, 3, 8, 9]
a_as_set = set(a)
intersection =x_as_set.intersection(y)
intersection_as_list = list(intersection)
print(intersection_as_list)

And its output will be:

[1, 9]

 Happy coding.

35k points