[Tutor] Finding the differences between two lists

Robert Sjoblom robert.sjoblom at gmail.com
Thu Aug 25 21:48:40 CEST 2011


> Scenario: I have a list of MAC addresses that are known and good, and am
> comparing it to a list of MACs found in a scan.  I want to weed out the
> those which are unknown.  I am using IDLE (Python 2.7) on Windows, and all
> files are in the same directory.
>
> Code:
>
> scanResults = open('scanResults.txt', 'r')
> verifiedList = open('verifiedList.txt', 'r')

You don't close the files after you open them, which is bad practice.
"with" is a great keyword, because it closes the file once it's run
its block of code. We'll use that:

with open("scanResults.txt", "r") as f:      #open scanResults.txt and
put the file object in variable f
    scanResults = f.readlines()                  #once this finishes
scanResults.txt is closed
with open("verifiedList.txt", "r") as f:
    verifiedList = f.readlines()

> badMacs = []
> for mac in scanResults:
>  if mac not in verifiedList:
>    print mac
>    badMacs.append(mac)
>  else:
>    break

I can't say for sure, since I don't know how your logs look, but this
loop will break at the first match (I think!). You could try changing
the break statement to a continue statement (or just ignoring it
altogether -- if it's in verifiedList you don't need to do anything).
Anyway, list comprehensions are something I've been experimenting with
lately, because I need the practice, so I'm going to suggest that
instead:
badMacs = [item for item in scanResults if item not in verifiedList]

Other than that, there's not much to say; the standard is 4 spaces
indentation, personally I feel that 1 space is too little, since it's
hard to see where one block ends and another begins.

best regards,
Robert S.


More information about the Tutor mailing list