# Find common elements in two lists python

1 vote
30 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

1 vote

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.

## Related questions

1 vote
68 views
Problem: I am new to programming language. I was trying to find common elements in two lists using python. So I wrote this code: a = [1, 2, 6, 9] b = [1, 3, 8, 9] a_as_set = set(b) intersection =a_as_set.intersection(b) intersection_as_list = list(intersection) print(intersection_as_list) This code gives me the output: [8, 1, 3, 9] Which is not right. Please help me to get the exact output.
42 views
Problem: I have two ArrayList objects with three integers each. I want to find a way to return the common elements of the two lists Use Collection#retainAll(). listA.retainAll(listB); // listA now contains only the elements which are also contained in listB.
27 views
1 vote
22 views
Problem: Hello kodlogs, I know the core python but when I have to implement the list concept with this that applying with two lists don't know how to implement this having issue, basically, I come from the c background and in c language there was not any concept of this ... I can see the content of the list is same still I am getting the error dont know how to achieve this waiting for the reply.
4 views
Problem: I will request someone to answer my question Please, I have searched on the web but I got no useful information for this, now I am in difficulty continuing my learning
1 vote
48 views
Problem: Hello Kodlogs, I am struggling to solve a problem based on Python. I was solving basic-level problems from a website. I&rsquo;ve got a question today that says to find the intersection of two lists using Python codes. I didn&rsquo;t get the facts here. Could you please elaborate on the things clearly? Thanks!
1 vote
4 views
Problem: Please help me. How can I solve it? python check if two lists have same elements