Blaine
Blaine

Reputation: 667

Is there a pythonic way to iterate through the difference of two lists?

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

Answers (3)

Cory Kramer
Cory Kramer

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

chepner
chepner

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

lhk
lhk

Reputation: 30046

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)

Upvotes: 6

Related Questions