How Can We Help?
Lists are a prevalent data type in the programming world. Not only in python, but this data type is used in almost all languages to store values of similar data types.
This article will explain how to compare two lists in python using different techniques, which are:
- Compare two lists using the ‘==’ Operator.
- Compare two lists using Iterations.
- Compare two lists using reducer and map Functions.
- Compare two lists using the Dictionary Method.
- Compare two lists using the Collection Method.
- Compare two lists using the set Function Method.
- Compare two lists by Checking If The Lists Have Any Unique Elements.
Comparing Through ‘==’ Operator
The simplest way to compare two lists is to use the ‘==’ operator. The operator returns True if the two lists are equal and False otherwise.
Example (1)
firstList = [12, 23, 89, 75, 65]
secondList = [12, 23, 3, 4, 5]
thirdList = [12, 23, 89, 75, 65]
if (firstList == thirdList):
print("The firstList and thirdList are the same")
else:
print("The firstList and thirdList are not equal")
if (firstList == secondList):
print("The firstList and secondList are identical")
else:
print("The firstList and secondList are different")
Output:
The firstList and thirdList are identical
The firstList and secondList are different
First, we defined the lists. Next, we use the ‘==’ operator to check if the lists are equal. We printed messages based on the return value.
Class-based implementation of the above approach is as follows:
Example (2)
class Check:
def __init__(self,list_one,list_two):
self.one=list_one
self.two=list_two
def compare_lists(self):
if(self.one==self.two):
return True
else:
return False
# Defining the first list
list_1 = [10, 20, 30, 5]
# Defining the second list
list_2 = [10, 20, 30, 50]
check=Check(list_1,list_2)
if(check.compare_lists):
print("The lists are identical")
else:
print("The lists are different")
Output:
The lists are identical
If we only want to check if there are the same elements in the two given lists and we do not care about the order in which they are arranged, then we should first sort the elements of the lists.
Example (3)
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
l1.sort()
l2.sort()
l3.sort()
if (l1 == l3):
print("The lists are the same")
else:
print("The lists are not equal")
if (l1 == l2):
print("The lists are equal")
else:
print("The lists are not equal")
Output:
The lists are identical
The lists are different
Comparing The Lists Through Iterations
The simplest way to check if two lists are equal or not is by the method of iteration. We can adopt the following form to compare two lists:
First, define a flag. Next, iterate through the lists, and during each iteration, check if the element at the indices are equal.
If the elements are equal, then update the values of the variables and proceed to the next iteration. However, if the elements are unequal, break away from the iterating step and update the flag’s value.
Example (4)
# Defining the first list
list_1 = [10, 20, 30, 50]
# Defining the second list
list_2 = [10, 20, 30, 50]
# Initializing the flag to be True
flag=True
i=0
j=0
# Interating through the lists
while(i<len(list_1) and j<len(list_2)):
# Comparing the elements of the lists
if(list_1[i]!=list_2[j]):
# If the elements do not match, then update the value of the flag to False
flag=False
# Break away from the loop
break
# If the elements are equal, then update the value of i and j
else:
j=j+1
i=i+1
# Print depending on whether the lists are equal or not
if(flag):
print('Two lists are identical')
else:
print('Three lists are different')
Output:
Two lists are identical
Explanation:
- First, we defined the two lists.
- Next, we defined a flag and initialized the value to be True. Next, we initialized other variables like i and j, which we later used for the iteration through the lists.
- Next, we iterated through the first list and compared if the elements of the first list were equal to the element of the second list. If the elements are not equal, we update the flag’s value and break away from the iteration.
- If, however, the elements of the lists are equal, then we update the values of i and j by incrementing them by 1.
- Finally, we printed messages based on the values of the flag.
We can also slightly tweak the above approach to get similar results as follows:
Example (5)
# Defining the first list
list_1 = [10, 20, 30, 5]
# Defining the second list
list_2 = [10, 20, 30, 50]
# Initializing the flag to be True
flag=True
i=0
j=0
# Interating through the lists
for i in range(len(list_1)):
# Comparing the elements of the lists
if(list_1[i]!=list_2[j]):
# If the elements do not match, then update the value of the flag to False
flag=False
# Break away from the loop
break
# If the elements are equal, then update the value of i and j
else:
j=j+1
i=i+1
# Print depending on whether the lists are equal or not
if(flag):
print('Two lists are identical')
else:
print('The lists are different')
Output:
The lists are different
Using The Reducer And The Map Functions
We can use the combination of the map and the reduce function to compare the lists in python. Before discussing the implementation, we should understand the usage of both of them. The map function is a trendy function among developers. It accepts two arguments. First is the function which needs to be applied to the iterables, and the second is the iterables on which the function is to be applied. The iterables can be in the form of strings, lists, tuples, etc. On the other hand, the reduce function applies the passed function to all the elements of the iterable recursively. So in the first step, it would apply the method up to the second element, and eventually, the process will continue until the last element of the list.
We can adopt both functions in our code to compare two lists. The map function will apply functions to the iterables, and the reduce function will make sure to apply that function to all the elements in a consecutive manner.
Note: The reduce function is from the functools library.
Example (6)
# Import all the necessary packages and libraries in the code
import functools
# Define the lists
firstList = [12,23,89,75,65]
secondList = [12,23,3,4,5]
thirdList = [12,23,89,75,65]
fourthList = [3,23,1,7,65]
# Compare the lists
if functools.reduce(lambda v, l : v and l, map(lambda a, b: a == b,firstList,secondList), True):
print ("The firstList and thirdList are identical")
else:
print ("The firstList and thirdList are different")
if functools.reduce(lambda v, l : v and l, map(lambda a, b: a == b,firstList,thirdList), True):
print ("The firstList and thirdList are identical")
else:
print ("The firstList and thirdList are different")
if functools.reduce(lambda v, l : v and l, map(lambda a, b: a == b,secondList,fourthList), True):
print ("The secondList and thirdList are identical")
else:
print ("The secondList and thirdList are different")
Output:
The firstList and thirdList are different
The firstList and thirdList are identical
The secondList and thirdList are different
Using the Dictionary Method to Compare two Lists
We can adopt many indirect methods to check if two lists are equal. One of the most efficient methods is discussed below:
- First, store the element and the frequency in the form of a dictionary.
- For each list, there will be a corresponding dictionary.
- Next, compare the two dictionaries. If the dictionary is equal, that means each element of the list occurred the same number of times; hence, they are equal. Otherwise, they are not equal.
Example (7)
# Inilializing the lists
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
# Creating a new empty list
l1_new = []
l2_new = []
l3_new = []
# Iterating through the first list
for i in l1:
# Cheking whether the element is present in the new list
if (i in l1_new):
# If it is present in the new list, then continue the loop
continue
else:
# If the element is not present in the new list, then append it to the new list
l1_new.append(i)
# Below two iterations follow a similar procedure as the previous one
for i in l2:
if (i in l2_new):
continue
else:
l2_new.append(i)
for i in l3:
if (i in l3_new):
continue
else:
l3_new.append(i)
# Print the new lists
print(l1_new)
print(l2_new)
print(l3_new)
# Inilializing three empty dictionaries
dict_1 = {}
dict_2 = {}
dict_3 = {}
# Iterationg through the new list and then stored as a key-value pair in the dictionary
for i in l1_new:
dict_1[i] = l1.count(i)
print(dict_1)
for i in l2_new:
dict_2[i] = l2.count(i)
for i in l3_new:
dict_3[i] = l3.count(i)
print(dict_2)
# Comparing the first and the second dictionary
if (dict_1 == dict_2):
print("Two lists are equal")
else:
print("Two lists are not equal")
if (dict_1 == dict_3):
print("Two lists are equal")
else:
print("Two lists are not equal")
Output:
[12, 23, 89, 75, 65]
[12, 23, 3, 4, 5]
[12, 23, 89, 65, 75]
{12: 1, 23: 1, 89: 1, 75: 1, 65: 1}
{12: 1, 23: 1, 3: 1, 4: 1, 5: 1}
Two lists are not equal
Two lists are equal
Explanation:
- First, we defined the lists. Next, we created new empty lists where we later stored the unique values of the lists.
- Next, we iterated through the first list, and under each iterating step, we checked if the present element was also within the new list. If the element is present, then we continue. However, if the element is not present, we appended the element to the new list.
- We did a similar procedure for the first and the third lists. We printed the updated values of the new lists.
- Next, we created empty dictionaries. We again iterated through the new lists and stored them as a key-value pair in the dictionaries.
- We then compared the dictionaries to check if the lists were equal.
Class-based implementation of the above approach is as follows:
Example (8)
class Check:
def __init__(self, list_one, list_two):
self.one = list_one
self.two = list_two
def compare_lists(self):
l1_new = []
l2_new = []
# Inilializing three empty dictionaries
dict_1 = {}
dict_2 = {}
# Iterating through the first list
for i in self.one:
# Cheking whether the element is present in the new list
if (i in l1_new):
# If it is present in the new list, then continue the loop
continue
else:
# If the element does not exist in the new list, then append it to the new list
l1_new.append(i)
for i in self.two:
# Cheking whether the element is present in the new list
if (i in l2_new):
# If it is present in the new list, then continue the loop
continue
else:
# If the element does not exist in the new list, then append it to the new list
l2_new.append(i)
for i in l1_new:
dict_1[i] = self.one.count(i)
for i in l2_new:
dict_2[i] = self.two.count(i)
# Comparing the first and the second dictionary
if (dict_1 == dict_2):
return True
else:
return False
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
# Creating the object
check1 = Check(l1, l2)
check2 = Check(l1, l3)
check2 = Check(l1, l3)
# Comparing two lists
if (check1.compare_lists() == True):
print("The lists are equal")
else:
print("The lists are not equal")
if (check2.compare_lists() == True):
print("The lists are equal")
else:
print("The lists are not equal")
Output:
The lists are not equal
The lists are equal
Using The Collection Method to Compare Lists
The collection method is very similar to the previous implementation we discussed. In this method, we use a function called collections instead of using a dictionary. Internally the function maps and stores the elements and the corresponding frequency of the elements. If both lists are equal, they must have the same Counter values.
Example (9)
# Import the necessary libraries and packages in the code
import collections
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
# Using the Counter function to
print(collections.Counter(l1))
print(collections.Counter(l2))
print(collections.Counter(l3))
# Comparing the COunter of two lists
if collections.Counter(l1) == collections.Counter(l2):
print ("The lists l1 and l2 are identical")
else:
print ("The lists l1 and l2 are different")
if collections.Counter(l1) == collections.Counter(l3):
print ("The lists l1 and l3 are identical")
else:
print ("The lists l1 and l3 are different")
Output:
Counter({12: 1, 23: 1, 89: 1, 75: 1, 65: 1})
Counter({12: 1, 23: 1, 3: 1, 4: 1, 5: 1})
Counter({12: 1, 23: 1, 89: 1, 75: 1, 65: 1})
The lists l1 and l2 are different
The lists l1 and l3 are identical
We can have the class-based implementation of the above approach as follows:
Example (10)
# Import the necessary libraries and packages in the code
import collections
class Check:
# Defining the constructor
def __init__(self, list_one, list_two):
self.one = list_one
self.two = list_two
def compare_lists(self):
if collections.Counter(self.one) == collections.Counter(self.two):
return True
else:
return False
# Defining the lists
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
# Creating the first object
check1 = Check(l1, l2)
# Checking the output of the comparison
if (check1.compare_lists()):
print("The first and the second lists are identical")
else:
print("The first and second lists are different")
# Creating the second object
check2 = Check(l1, l3)
# Checking the output of the comparison
if (check2.compare_lists()):
print("First and the third lists are identical")
else:
print("First and third lists are different")
Output:
The first and second lists are different
The first and the second lists are identical
Using The set Function to Compare Lists
This is another indirect method we can apply to compare the lists. Under this method, we first convert the lists into sets. Next, we can use the ‘==’ operator to compare the two sets.
Example (11)
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
a = set(l1)
b = set(l3)
print(a)
print(b)
if a == b:
print("The lists are equal")
else:
print("The lists are not equal")
Output:
{65, 75, 12, 23, 89}
{65, 75, 12, 23, 89}
The lists are equal
Class-based implementation of the above approach is as follows:
Example (12)
l1 = [10, 20, 30, 40, 50]
l3 = [50, 10, 30, 20, 40]
class Check:
# Defining the constructor
def __init__(self, list_one, list_two):
self.one = list_one
self.two = list_two
def compare_lists(self):
a = set(self.one)
b = set(self.two)
if (a == b):
return True
else:
return False
# Defining the lists
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
# Creating the first object
check1 = Check(l1, l2)
# Checking the output of the comparison
if (check1.compare_lists()):
print("The first and the second lists are identical")
else:
print("The first and second lists are different")
# Creating the second object
check2 = Check(l1, l3)
# Checking the output of the comparison
if (check2.compare_lists()):
print("First and the third lists are identical")
else:
print("First and third lists are different")
Output:
The first and second lists are different
The first and the third lists are identical
Checking If The Lists have Any Unique Elements
Another very tricky approach is first to check if any element in any list is not present in the second list. If any element is not present in both lists, then the lists are not equal.
Example (13)
firstList = [12, 23, 89, 75, 65]
secondList = [12, 23, 3, 4, 5]
thirdList = [12, 23, 89, 75, 65]
ans1 = [z for z in firstList + secondList if z not in firstList or z not in secondList]
ans2 = [z for z in firstList + thirdList if z not in firstList or z not in thirdList]
print(ans1)
print(ans2)
if(ans1):
print("The list are not the same")
else:
print("The lists are identical")
if(ans2):
print("The lists are not the same")
else:
print("The lists are identical")
Output:
[89, 75, 65, 3, 4, 5]
[]
The lists are not the same
The lists are identical
We can have a class-based implementation of the above approach as follows:
Example (14)
# Creating the class
class Check:
# Defining the constructor
def __init__(self, list_one, list_two):
self.one = list_one
self.two = list_two
def compare_lists(self):
# Using the list comprehension
ans = [x for x in self.one +
self.two if x not in self.one or x not in self.two]
return ans
# Defining the lists
l1 = [12, 23, 89, 75, 65]
l2 = [12, 23, 3, 4, 5]
l3 = [12, 23, 89, 75, 65]
# Defining the object
check1 = Check(l1, l2)
check2 = Check(l1, l3)
if (check1.compare_lists()):
print("The list are equal")
else:
print("The lists are not equal")
if (check2.compare_lists()):
print("The list are equal")
else:
print("The lists are not equal")
Output:
The lists are equal
The lists are not equal
Final Thoughts
In this article, we have understood how to compare two lists in python. We saw the operators, functions, etc. techniques to achieve the same. Along with them, we also saw how to use external libraries to check the lists.
We strongly recommend that the readers practice all the methods discussed to understand the concept well.