-1

I have 2 lists that have a few similar value, what I want is to print out the values that are only in both lists. I tried a list comprehension but it gives me a boolean list:

a=[2,3,1,5,7]
b=[2,5,9,3,5,10]
c=[d in a for d in b]
print (c)

from this I get the results below:

[True, True, False, True, True, False]

but I wanted the numbers familiar in both lists.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 2
    Possible duplicate of [How to check if one of the following items is in a list?](https://stackoverflow.com/questions/740287/how-to-check-if-one-of-the-following-items-is-in-a-list) – Sheldore Sep 23 '18 at 10:02
  • 1
    Have you considered using sets instead, they have features for such calculations. – Klaus D. Sep 23 '18 at 10:02

3 Answers3

3

You can conditionally take only the d that are in a from b:

c = [d for d in b if d in a]
# Here -----------^
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

let us see this code :[d in a for d in b], d in a will return True or False because it equal to

if d in a:
    return True 
else:
    return False

So the result of [d in a for d in b] is [True, True, False, True, True, False]

The best way to wanted the numbers familiar in both lists is:

a=[2,3,1,5,7]
b=[2,5,9,3,5,10]
print(list(set(a) & set(b))) # [2, 3, 5]
KC.
  • 2,981
  • 2
  • 12
  • 22
0

You could use a set to compare the values, however I don't believe this preserves order:

c = set(a) & set(b)
print('\n'.join(str(i) for i in c))
N Chauhan
  • 3,407
  • 2
  • 7
  • 21