Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two list and output missing and extra element (Python)

Tags:

python

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
like image 704
Michael Avatar asked May 09 '17 01:05

Michael


People also ask

How do you find the additional element in a list while comparing two lists?

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.

How do you compare two unequal lists in Python?

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.

How do you compare elements in a list with another list in Python?

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.


1 Answers

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']
like image 95
ATSTNG Avatar answered Oct 20 '22 16:10

ATSTNG