How to compare ’n’ number of flat lists in Python ?

Rupali Mishra
2 min readJul 3, 2021

You might have encountered situation when you have ’n’ number of lists available over excel, notepad etc and you want to compare them.
But the thing is Python takes the list and each element in the list should be properly quoted and separated by ‘,’. What’s the easiest way to compare such list if they are not in the desired shape.
Example : You have two lists as below :
list_1 =
a
b
c

list_2 =
b
d
e

What Python wants ?
list_1 = [‘a’, ‘b’, ‘c’]
list_2 = [‘b’,‘d’, ‘e’], now there are plenty of ways to do that, but let’s look over one of them.
Copy and paste both the lists in fresh new excel sheet and name each column independently as ‘list_1’ , ‘list_2’.

excel_sheet_snipet

Name you excel sheet, let’s say ‘compare.xlsx’ & give some sheet name as per your convenience and save.
Now, run the simple lines of code that will do the job for you quick.
Install openpyxl using, pip install openpyxl if not already present.
What’s openpyxl — A python library to read xls, refer https://openpyxl.readthedocs.io/en/stable/ for more details.

import pandas as pd

if __name__ == '__main__':
df = pd.read_excel('compare.xlsx', sheet_name='sheet_1', engine='openpyxl')
list_1 = df['list_1'].tolist()
list_2 = df['list_2'].tolist()

diff_list = []
for i in list_1 :
if i in list_2:
continue
else:
diff_list.append(i)

print(diff_list)

‘diff_list’ will print the difference of elements between both the lists. Job is done.!!

--

--

Rupali Mishra

Engineer who is curious to be better one #developer #coder #python #java #explorer