Python Forum
Find Common Elements in 2 list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Find Common Elements in 2 list (/thread-33308.html)



Find Common Elements in 2 list - quest - Apr-14-2021

Hello
I have this list:
A [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
B [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]

I want to find number of same elements in the list
I tried these methods but the result is always zero:
list1_as_set = set(A)
intersection = list1_as_set.intersection(B)
intersection_as_list = list(intersection)
I also tried that one:
commonalities = set(A) - (set(A) - set(B))
But the result is empty ..
How can I find the common elements in 2 different list?


RE: Find Common Elements in 2 list - klllmmm - Apr-14-2021

Hope this helps
A = [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
B = [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]

list(set(A).intersection(B))
Output:
[(37.5,), (40.0,), (30.0,), (27.5,), (17.5,), (25.0,), (22.5,)]



RE: Find Common Elements in 2 list - Larz60+ - Apr-14-2021

>>> A = [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
>>> B = [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]
>>> set(A).union(set(B))
{(37.5,), (40.0,), (30.0,), (27.5,), (17.5,), (7.5,), (42.5,), (25.0,), (22.5,)}
>>>
>>>
>>> # With lists better formatted:
>>> A = [7.5, 17.5, 22.5, 25.0, 27.5, 30.0, 37.5, 40.0]
>>> B = [17.5 22.5, 25.0, 27.5, 30.0, 37.5, 40.0, 42.5]
>>> set(A).union(set(B))
{37.5, 7.5, 40.0, 42.5, 17.5, 22.5, 25.0, 27.5, 30.0}
>>>



RE: Find Common Elements in 2 list - quest - Apr-14-2021

(Apr-14-2021, 03:29 PM)klllmmm Wrote: Hope this helps
A = [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
B = [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]

list(set(A).intersection(B))
Output:
[(37.5,), (40.0,), (30.0,), (27.5,), (17.5,), (25.0,), (22.5,)]

I have still empty list as a result ... Huh


RE: Find Common Elements in 2 list - quest - Apr-14-2021

(Apr-14-2021, 03:29 PM)klllmmm Wrote: Hope this helps
A = [(7.5,), (17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,)]
B = [(17.5,), (22.5,), (25.0,), (27.5,), (30.0,), (37.5,), (40.0,), (42.5,)]

list(set(A).intersection(B))
Output:
[(37.5,), (40.0,), (30.0,), (27.5,), (17.5,), (25.0,), (22.5,)]
It is ok now
THanks!