Python Forum

Full Version: Find Common Elements in 2 list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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,)]
>>> 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}
>>>
(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
(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!