Edit: Removed undefined variable. So my code is basically, trying to compare if a value of one list is present in another. If so append the value to 3rd list. If the value is not present, then append to 4th list. What is the most efficient and readable way to do this task. Example of my code:
a = [1,2,3]
b = [2,3,4,5,6,7]
c = []
d = []
for ele in a:
if ele in b:
c.append(ele )
else:
d.append(ele)
CodePudding user response:
a=[2,3,4,5]
b=[3,5,7,9]
c = [value for value in a if value in b]
d = [value for value in a if value not in b]
print(f'Present in B: {c}')
print(f"Not present in B: {d}")
CodePudding user response:
c = [i for i in a if i in b]
d = [i for i in a if i not in b]
CodePudding user response:
The best way to solve this is by using sets.
import random
a = [random.randint(1, 15) for _ in range(5)]
b = [random.randint(1, 15) for _ in range(7)]
print(a)
print(b)
set_a = set(a)
set_b = set(b)
set_intersection = set_a.intersection(set_b)
set_diff = set_a.difference(set_b)
print(list(set_intersection))
print(list(set_diff))
