tim67
tim67

Reputation: 15

Check if element exist in list

I'm new to python. I have two lists. The first one is ipaddress= [['10.25.16.201'], ['10.25.16.202'], ['10.25.16.203'], ['10.90.90.10']] and the second one is newipaddress =[["10.110.34.50"], ["10.25.17.212"], ["10.90.90.10"]]

How can I check ipaddress to verify if it contains an element from newipaddress? This is what I've tried. Thanks in advance!

for x in ipAddress:
    print(x)
    for y in newipaddress:
        print(y)
        if (y in x):
            print(y)

Upvotes: 0

Views: 1650

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

We can avoid loops altogether and instead use a list comprehension:

ipaddress = [['10.25.16.201'], ['10.25.16.202'], ['10.25.16.203'], ['10.90.90.10']]
newipaddress = [["10.110.34.50"], ["10.25.17.212"], ["10.90.90.10"]]
output = [x in newipaddress for x in ipaddress]
print(output)  # [False, False, False, True]

To display the element in the first list, if it exist in the second list, use:

output = [x for x in ipaddress if x in newipaddress]
print(output)  # [['10.90.90.10']]

Upvotes: 4

BossTrolley
BossTrolley

Reputation: 51

you can use 'if x in' to accomplish what you're after:

for x in ipaddress:
    if x in newipaddress:
        print('ip in newipaddress:', x)

Upvotes: 0

Related Questions