Reputation: 667
My goal is to iterate through the difference of two lists
I attempted a bodge code to write a - b as follows
for i in a:
if i in b:
continue
#statements
I was wondering if there was a more pythonic/efficient way of doing this.
Upvotes: 4
Views: 66
Reputation: 117856
In terms of sets, the items in a
but not in b
would be the set difference, therefore this would be
for i in set(a).difference(b):
# statements
Upvotes: 1
Reputation: 531055
What you have is fine. If you object to the continue
statement, you can iterate over a generator:
for i in (x for x in a if x not in b):
though that is arguably worse in terms of readability.
Upvotes: 0