Reputation: 1
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?
Upvotes: 0
Views: 88
Reputation: 1
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.
Upvotes: 0
Reputation: 1425
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}
Upvotes: 1