The Wayback Machine - https://web.archive.org/web/20240805133839/https://www.geeksforgeeks.org/python-difference-two-lists/
Open In App

Python | Difference between two lists

Last Updated : 29 Dec, 2023
Comments
Improve
Suggest changes
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

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 | Check if two lists have at-least one element common
Given two lists a, b. Check if two lists have at least one element common in them. Examples: Input : a = [1, 2, 3, 4, 5] b = [5, 6, 7, 8, 9] Output : True Input : a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9] Output : FalseMethod 1: Traversal of List Using traversal in two lists, we can check if there exists one common element at least in them. While traversing
5 min read
Python | Check whether two lists are circularly identical
Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 1
5 min read
Python | Print all the common elements of two lists
Given two lists, print all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output : {5} Explanation: The common element of the lists is 5. Input : list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output : No common elements Explanation: They do not have any elements in common in between them Method 1:
8 min read
Python Program to Split the Even and Odd elements into two different lists
In this program, a list is accepted with a mixture of odd and even elements and based on whether the element is even or odd, it is Split the Even and Odd elements using Python. Examples Input: [8, 12, 15, 9, 3, 11, 26, 23] Output: Even lists: [8, 12, 26] Odd lists: [15, 9, 3, 11, 23] Input: [2, 5, 13, 17, 51, 62, 73, 84, 95] Output: Even lists: [2,
2 min read
Python | Find missing and additional values in two lists
Given two lists, find the missing and additional values in both the lists. Examples: Input : list1 = [1, 2, 3, 4, 5, 6] list2 = [4, 5, 6, 7, 8] Output : Missing values in list1 = [8, 7] Additional values in list1 = [1, 2, 3] Missing values in list2 = [1, 2, 3] Additional values in list2 = [7, 8] Explanation: Approach: To find the missing elements o
3 min read
Python | Check if two lists are identical
This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1: Using list.sort() and == operator sort() coupled with == operator can achieve this task. We f
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg