Reputation: 1505
I have two lists. I want to be able to iterate using for loops, and want to do some operation on the element based on matched element. I cannot figure out what going wrong here,
lst1 = ["a1", "b1", "c1", "d1", "e1", "f1", "g1"]
lst2 = ["c1", "d1", "e1"]
for l in lst1:
for m in lst2:
if l == m:
v = l + "__match_found"
else:
v = l + "__no_match"
print(v)
I am getting following output:
a1__no_match
b1__no_match
c1__no_match
d1__no_match
e1__match_found
f1__no_match
g1__no_match
I am expecting that each element should only be printed once, either with match, or no_match the end.
Upvotes: 1
Views: 2929
Reputation: 23146
In your code, when l
is c1
, in each iteration of your inner loop:
m
is c1
: v = l + "__match_found"
m
is d1
: v = l + "__no_match"
m
is e1
: v = l + "__no_match"
You then print only the final value of v.
Instead, when you find a match, you should be using break
to dis-continue the inner loop:
for l in lst1:
for m in lst2:
if l == m:
v = l + "__match_found"
break
else:
v = l + "__no_match"
print(v)
A cleaner way to do this would be using in
:
for l in lst1:
if l in lst2:
print (l + "__match_found")
else:
print (l + "__no_match")
Upvotes: 1
Reputation: 114330
Since you print v
in the outer loop, you will get whatever the last value of m
assigned to it. This is not what you want: you want to break
out of the inner loop as soon as you find a match:
for l in lst1:
v = l + "__no_match"
for m in lst2:
if l == m:
v = l + "__match_found"
break
print(v)
Now let's simplify the and make it more pythonic. First, the inner loop is just a check for containment. In python, that's usually done with the in
operator:
for l in lst1:
v = "__match_found" if l in lst2 else "__no_match"
print(l + v)
Now if your only goal is to check for containment, you are much better off using set
than list
as your container. For example:
s1 = set(lst1)
s2 = set(lst2)
for i in s1 & s2:
print(i + '__match_found')
for i in s1 - s2:
print(i + '__no_match')
These operations are done with hashables, and are much faster than the linear lookup of lists.
Upvotes: 1