I have two lists of different sizes (one may be larger than the other), with some common elements. I would like to get items nfrom the first list that are not in the second.
I see two families of solutions (example below for n=3)
a = [i for i in range(2, 10)]
b = [i * 2 for i in range (1, 10)]
s1 = list(set(a) - set(b))
s2 = [i for i in a if i not in b]
for i in [s1, s2]:
print (i[:3])
c = 0
s3 = []
for i in a:
if i not in b:
s3.append(i)
c += 1
if c == 3:
break
print(s3)
They are all true, way out
[9, 3, 5]
[3, 5, 7]
[3, 5, 7]
(the first solution does not give the first 3, because it setdoes not preserve order - but this is normal in my case, since in any case I will have unsorted (even obviously shuffled) lists)
Are the most pythonic and reasonably optimal?
Solution 1 first calculates the difference, then slices, which I find rather ineffective (the size of my lists will be ~ 100 thousand elements, I will look for the first 100).
2 , ( , , , - Python, , ).
2, .