Learner
Learner

Reputation: 691

Iterate lists elements within two for loops

I have a list as

A= ['loans', 'mercedez', 'bugatti', 'a4', 'trump', 'usa', 'election', 'president', 'galaxy', '7s', 'canon', 'macbook', 'beiber', 'spiderman', 'marvels', 'ironmen']

and

B=['loans','network','washington','trump','canon','london']

When I did something as in order to get words from B which were not present in list A :

for i in A:
    for j in B:
        if j not in i:
            print (j)

It gives cycle of loops as:-

network
washington
trump
canon
london
loans
network
washington
trump
canon
london
loans
network
washington
trump
canon
london
loans
network
washington
trump
canon
london
.......
.......
.......

Why So? All I want to return

network
washington
london

Upvotes: 1

Views: 61

Answers (4)

Kushan Gunasekera
Kushan Gunasekera

Reputation: 8606

Try this,

A = ['loans', 'mercedez', 'bugatti', 'a4', 'trump', 'usa', 'election', 'president', 'galaxy', '7s', 'canon', 'macbook', 'beiber', 'spiderman', 'marvels', 'ironmen']
B = ['loans', 'network', 'washington', 'trump', 'canon', 'london']
print('\n'.join([i for i in B if i not in A]))

output:

network
washington
london

Upvotes: 0

vash_the_stampede
vash_the_stampede

Reputation: 4606

Use set difference

print(set(B) - set(A))

Upvotes: 0

kerwei
kerwei

Reputation: 1842

Make use of the not in method:

not_in_list = [b for b in B if b not in A]

for n in not_in_list:
    print(n)

For better clarity, your original code would work if it's written as follow:

for b in B:
    unique = True
    for a in A:
        if b == a:
            unique = False
            break

    if unique == True:
        print(b)

Upvotes: 2

Rémi Baudoux
Rémi Baudoux

Reputation: 559

for i in B:
    if i not in A:
        print (i)

Upvotes: 3

Related Questions