I've 2 lists(sorted) of prefix and would like to compare it in Python so that I can output which element in the original list was missing and which was added.
Eg.
list1_original = ['1.1.1.1/24','2.2.2.2/24','3.3.3.3/24','4.4.4.4/24']
list2 = ['3.3.3.3/24','4.4.4.4/24','5.5.5.5/24','6.6.6.6/24']
I want to compare the 2 lists and output the add/remove element in list1_original. ie:
1.1.1.1/24, 2.2.2.2/24 = missing
5.5.5.5/24, 6.6.6.6/24 = added
To find the additional elements in list1, calculate the difference of list1 from list2. Insert the list1 and list2 to set and then use difference function in sets to get the required answer.
The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.
sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.
If there is no duplicates in given lists you may use sets and their "-" operator:
list1 = ['1.1.1.1/24', '2.2.2.2/24', '3.3.3.3/24', '4.4.4.4/24']
list2 = ['3.3.3.3/24', '4.4.4.4/24', '5.5.5.5/24', '6.6.6.6/24']
set1 = set(list1)
set2 = set(list2)
missing = list(sorted(set1 - set2))
added = list(sorted(set2 - set1))
print('missing:', missing)
print('added:', added)
this prints
missing: ['1.1.1.1/24', '2.2.2.2/24']
added: ['5.5.5.5/24', '6.6.6.6/24']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With