0

For example:

if two lists elements are

a = [1,2,3,4,5]
b = [2,3,4,5,6]

and I want to get [2,3,4,5] because its sharing the same number? Can somebody help me?

Oh, and by the way, how to wrote the code if the a and b is random list?

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
  • Does this answer your question? [How to find list intersection?](https://stackoverflow.com/questions/3697432/how-to-find-list-intersection) – dspencer Apr 08 '20 at 15:39

2 Answers2

1

You can either use list comprehension or set union:

a = [1,2,3,4,5]
b = [2,3,4,5,6]

res = [x for x in a if x in b]
res_set = set(a) & set(b)

print(res)     # [2, 3, 4, 5]
print(res_set) # {2, 3, 4, 5}
hurlenko
  • 1,363
  • 2
  • 12
  • 17
0
a = [1,2,3,4,5]
b = [2,3,4,5,6]

c=[x for x in a if x in b]
d=[y for y in (a+b) if y not in c]

print(c)    # [2, 3, 4, 5]
print(d)    # [1,6]

You can get the same element and get different elements.

Lining
  • 1
  • 3