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.
You could use sets, to look at the difference:
a = [1, 2, 3, 4, 5]
b = [2, 4, 6]
a = set(a)
b = set(b)
for i in a.difference(b):
print(i)
# even supports the arithmetic syntax :D
for i in a - b:
print(i)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With