Aniketan Aniketan - 3 months ago 11
Python Question

How to compare more than 2 Lists in Python?

I am new to Python as well new on Stackoverflow , can anyone tell me efficient(pythonic) way to compare more than 2 Lists ? I want to enlist all the elements of all 3 Lists and display in such fashion that user will be able to know that which element is present in all 3 List OR element present in List 1 but not in List 2 OR which elements are duplicates. I have done comparison using nested loops.

List1 = [10,10,11,12,15,16,18,19]
List2 = [10,11,13,15,16,19,20]
List3 = [10,11,11,12,15,19,21,23]

# Checking whether List 1 value present in List2 and List 3
for l1 in List1:
if l1 in List2:
List2.remove(l1)
if l1 in List3:
List3.remove(l1)
print(l1," ",l1," ",l1)
else:
print(l1," ",l1," ","NA")
else:
if l1 in List3:
List3.remove(l1)
print(l1," ","NA"," ",l1)
else:
print(l1," ","NA"," ","NA")

# Checking whether List 2 value present in List3
for l2 in List2:
if l2 in List3:
List3.remove(l2)
print("NA"," ",l2," ",l2)
else:
print("NA"," ",l2," ","NA")

# Checking for values present only in List 3

for l3 in List3:
print("NA","NA",l3)

--- Output---
List1 List2 List3
10 10 10
10 NA NA
11 11 11
12 NA 12
15 15 15
16 16 NA
18 NA NA
19 19 19
NA 13 NA
NA 20 NA
NA NA 11
NA NA 21
NA NA 23
NA 20 NA
NA NA 11
NA NA 21
NA NA 23


Is there any better way to compare the Lists ?

Answer
import pandas as pd
d = {'List1' : pd.Series(List1),'List2' : pd.Series(List2),'List3': pd.Series(List3)}

df = pd.DataFrame(d)

print(df)

***OUTPUT:***
      List1  List2  List3
      10      NaN     NaN
      11      11     11
      12      NaN     12
      15      15     15
      16      16     NaN
      18      NaN    NaN
      19      19     19
      NaN     13     NaN

Using Pandas you can compare the multiple list, while the empty coloumn would be automatically filled as NaN.

Pandas is a Data visualization library of python

Install pandas by : pip install pandas

Edited :

Gist Link: https://gist.github.com/gr8Adakron/b51cc060b5e6dcc030261586f7237232