Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check if Items are in list

Tags:

python

loops

list

I am trying to iterate through two lists and check if 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 print the item from list_1. The below code accomplishes this partially but because I am performing two for loops I am getting duplicate values of list_1. Can you please direct me in a Pythonic way to accomplish?

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
like image 759
MBasith Avatar asked May 13 '26 09:05

MBasith


2 Answers

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 approach above ensure that you either print x or i and we only print one value per element in list_1.

You could also write (which is the same thing as above but makes use of the ability to add an else to a for loop):

for i in list_1:
    for x in list_2:
        if i in x:
            print(x)
            break
    else:
        print(i)
like image 103
Simeon Visser Avatar answered May 14 '26 22:05

Simeon Visser


for i in list_1:
    found = False
    for x in list_2:
        if i in x:
            found = True
            print(x)
    if found == False:
        print(i)
like image 22
shamssss.169 Avatar answered May 14 '26 23:05

shamssss.169



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!