Home > Net >  Check if element exist in list
Check if element exist in list

Time:04-14

I'm new to python. I have two list. The first is ipaddress= [['10.25.16.201'], ['10.25.16.202'], ['10.25.16.203'], ['10.90.90.10']] and the second 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)

CodePudding user response:

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']]

CodePudding user response:

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)
  • Related