J.Chan
J.Chan

Reputation: 77

Python 'for loop' code not working as expected

I have this list of lists (I believe) as seen below labeled ‘output A’. I apply the standard ‘for loop’ code for looping through a list to remove duplicate items, and get OUTPUT B, identical to the OUTPUT A results. I need some help on understanding why the ‘for loop’ did not work as expected.

OUTPUT A

for hops in any_match(conn,r'((?:[0-9]{1,3}\.){3}[0-9]{1,3})'):
    ips = hops.split()
    print(ips)

['10.33.226.237']

['10.33.226.237']

['10.32.0.174']

['10.32.0.190']

['10.33.226.225']

['10.33.226.237']

OUTPUT B

for hops in any_match(conn,r'((?:[0-9]{1,3}\.){3}[0-9]{1,3})'):
    ips = hops.split()
    newlist = []
    for i in ips:
        if i not in newlist:
            newlist.append(i)
    print(newlist)

['10.33.226.237']

['10.33.226.237']

['10.32.0.174']

['10.32.0.190']

['10.33.226.225']

['10.33.226.237']

Upvotes: 0

Views: 61

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599470

There seems to be only one IP address per match; your split() call returns a list of one item only, so your nested loop only looks at that one item. Since you reset the duplicate list each iteration of the outer list, it is always empty.

I'm not quite sure why you are doing that split and loop anyway. Instead, initialize the list outside the loop, and drop those calls:

newlist = []
for ip in any_match(conn,r'((?:[0-9]{1,3}\.){3}[0-9]{1,3})'):
    if ip not in newlist:
        newlist.append(i)
print(newlist)

Upvotes: 1

Related Questions