Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 430
Blaine Avatar asked Mar 03 '23 08:03

Blaine


2 Answers

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)
like image 110
lhk Avatar answered Mar 05 '23 22:03

lhk


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
like image 39
Cory Kramer Avatar answered Mar 05 '23 20:03

Cory Kramer