1

So i have 2 lists and i need to delete everything excluding duplicates - from both. Example: a = [1,2,7,8] b = [1,2,5,9]

output: [1,2] ELSE (which is better) 1 2

  • Does this answer your question? [Common elements comparison between 2 lists](https://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists) – Georgy Oct 24 '20 at 13:13

4 Answers4

2

You can use intersection:

print(set(a).intersection(set(b)))
>>> {1, 2}
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
1

You want to use set

a = [1,2,7,8] 
b = [1,2,5,9]

result = list(sorted(set(a).intersection(set(b)))
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • This could be good decition,but sorting is a little bit earlier than deleting douplicates,so it shouldn't be here – ATTMr Cmailik Oct 23 '20 at 10:42
  • @ATTMrCmailik, it depends what version of python that set will be ordered by insertion or not. That is why `sorted` is there, to keep the original order – Netwave Oct 23 '20 at 10:48
1

On top of Maurice's answer, you can avoid calling set on b as it is taken care by intersection.

print(set(a).intersection(b))
nbohra
  • 21
  • 2
1

You can use list comprehension in this question. Like this:

print([i for i in a for j in b if i==j])
burcubelen
  • 23
  • 7