Python checks if items are in a list
I am trying to iterate over two lists and check if the items in list_1 are in list_2. If the item in list_1 is in list_2, I would like to print the item in list_2. If the item is NOT in list_2, I would like to print the item from list_1. The following code partially accomplishes this, but since I am doing two loops, I get duplicate list_1 values. Can you guide me on the pythonic path?
list_1 = ['A', 'B', 'C', 'D', 'Y', 'Z']
list_2 = ['Letter A',
'Letter C',
'Letter D',
'Letter H',
'Letter I',
'Letter Z']
for i in list_1:
for x in list_2:
if i in x:
print(x)
else:
print(i)
Current output:
Letter A
A
A
A
A
A
B
B
B
B
B
B
C
Letter C
C
C
C
C
D
D
Letter D
D
D
D
Y
Y
Y
Y
Y
Y
Z
Z
Z
Z
Z
Letter Z
Desired output:
Letter A
B
Letter C
Letter D
Y
Letter Z
source to share
You can write:
for i in list_1:
found = False
for x in list_2:
if i in x:
found = True
break
if found:
print(x)
else:
print(i)
The above approach ensures that you either print x
or i
and we only print one value for each item in list_1
.
You can also write (which is the same as above, but uses the ability to add a loop else
to the loop for
):
for i in list_1:
for x in list_2:
if i in x:
print(x)
break
else:
print(i)
source to share