Open In App

Python | Difference between two lists

Last Updated : 29 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Python programming, comparing two lists is a common task with multiple approaches. This article explores different methods for obtaining the dissimilarity between two lists, enhancing your proficiency in handling lists and data comparison in Python. Join us on this insightful journey into various strategies for discerning differences between lists.

Example

Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
list2 = [25, 40, 35] 
Output: [10, 15, 20, 30]
Explanation: resultant list = list1 - list2

 Note: When you have multiple same elements then this would not work. In that case, this code will simply remove the same elements.
In that case, you can maintain a count of each element in both lists.

Ways to Compare Two Lists in Python

There are various ways to compare two lists in Python. Here, we are discussing some generally used methods for comparing two lists in Python those are following.

  • Use “in” Method
  • Using List Comprehension
  • Use set() Function
  • Use Numpy
  • Using zip() Function
  • Count occurrences using Counter

Python “in” keyword to Compare Two Lists in Python

In this example code iterates through elements in list `li1`, and appends each element to `temp3` if it is not present in list `li2`. The final result in `temp3` contains elements from `li1` that are not present in `li2`.

Python3




li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
 
temp3 = []
for element in li1:
    if element not in li2:
        temp3.append(element)
 
print(temp3)


Output

[10, 15, 20, 30]

Difference Between Two Lists in Python Using a List comprehension

In this example code creates a set ‘s’ from the elements of list ‘li2’, and then generates a new list ‘temp3’ containing elements from list ‘li1’ that are not present in set ‘s’. Finally, it prints the elements in ‘temp3’.

Python3




li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
 
s = set(li2)
temp3 = [x for x in li1 if x not in s]
print(temp3)


Output

[10, 15, 20, 30]

Find the Difference Between Two Lists in Python using set()

In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator. For more references on set visit Sets in Python. It is a similar technique that we used previously. The only difference is, that we replaced the nested loops with the list comprehension syntax.

Python3




li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
 
s = set(li2)
temp3 = [x for x in li1 if x not in s]
print(temp3)


Output

[10, 15, 20, 30]

Use Numpy to Compare Two Lists in Python

The numpy.concatenate() function concatenate a sequence of arrays along an existing axis. In this example code uses NumPy to create arrays `li1` and `li2`, finds the set differences between them (`dif1` and `dif2`), and concatenates these differences into a single list (`temp3`), finally printing the result.

Python3




import numpy as np
li1 = np.array([10, 15, 20, 25, 30, 35, 40])
li2 = np.array([25, 40, 35])
 
dif1 = np.setdiff1d(li1, li2)
dif2 = np.setdiff1d(li2, li1)
 
temp3 = np.concatenate((dif1, dif2))
print(list(temp3))


Output

[10, 15, 20, 30]

Compare Two Lists in Python Using zip() Function

In this example code compares corresponding elements of two lists, li1 and li2, and creates a list of boolean values indicating whether the elements are equal. The `all` function checks if all elements in the result list are True.

Python3




li1 = [10, 15, 20]
li2 = [25, 40, 35]
 
result = [a == b for a, b in zip(li1, li2)]
print(all(result))


Output

False

Compare Two Lists Using Count Occurrences Using Counter

In this example code uses the `Counter` class from the `collections` module to create frequency counters for two lists, `li1` and `li2`. It then compares the counters to check if the lists have the same elements with the same frequencies, assigning the result to `are_lists_equal`.

Python3




from collections import Counter
 
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
 
counter1 = Counter(li1)
counter2 = Counter(li2)
 
are_lists_equal = counter1 == counter2
print(are_lists_equal)


Output

False


Previous Article
Next Article

Similar Reads

How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read
Python | Difference of two lists including duplicates
The ways to find difference of two lists has been discussed earlier, but sometimes, we require to remove only the specific occurrences of the elements as much they occur in other list. Let's discuss certain ways in which this can be performed. Method #1 : Using collections.Counter() The Counter method can be used to get the exact occurrence of the
5 min read
What Is Difference Between Del, Remove and Pop on Python Lists?
In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index. del Keyword: The del keyword delete any variable, list of values from a list
3 min read
Creating a sorted merged list of two unsorted lists in Python
We need to take two lists in Python and merge them into one. Finally, we display the sorted list. Examples: Input : list1 = [25, 18, 9, 41, 26, 31] list2 = [25, 45, 3, 32, 15, 20] Output : [3, 9, 15, 18, 20, 25, 25, 26, 31, 32, 41, 45] Input : list1 = ["suraj", "anand", "gaurav", "aman", "kishore"] list2 = ["rohan", "ram", "mohan", "priya", "komal"
1 min read
Python | Intersection of two lists
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. Examples: Input : lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output
4 min read
Python | Union of two or more Lists
Union of a list means, we must take all the elements from list A and list B (there can be more than two lists) and put them inside a single new list. There are various orders in which we can combine the lists. For e.g., we can maintain the repetition and order or remove the repeated elements in the final list and so on. Examples: Maintained repetit
7 min read
Python - Interleave two lists of different length
Given two lists of different lengths, the task is to write a Python program to get their elements alternatively and repeat the list elements of the smaller list till the larger list elements get exhausted. Examples: Input : test_list1 = ['a', 'b', 'c'], test_list2 = [5, 7, 3, 0, 1, 8, 4] Output : ['a', 5, 'b', 7, 'c', 3, 'a', 0, 'b', 1, 'c', 8, 'a'
3 min read
Article Tags :
Practice Tags :