There are various ways in which difference between two lists can be generated. In this article, we will see two most important ways in which this can be done. One by using the set() method, and another by not using it.
Examples:
Input :
list1 = [10, 15, 20, 25, 30, 35, 40]
list2 = [25, 40, 35]
Output :
[10, 20, 30, 15]
Explanation:
resultant list = list1 - list2
- By the use of 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 reference on set visit Sets in Python.
Example:
Python3
# Python code t get difference of two lists# Using set()def Diff(li1, li2): return (list(list(set(li1)-set(li2)) + list(set(li2)-set(li1))))# Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]print(Diff(li1, li2)) |
- Output :
[10, 20, 30, 15]
- Without using the set()
In this method, we use the basic combination technique to copy elements from both the list with a regular check if one is present in the other or not.
Python3
# Python code t get difference of two lists# Not using set()def Diff(li1, li2): li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2] return li_dif# Driver Codeli1 = [10, 15, 20, 25, 30, 35, 40]li2 = [25, 40, 35]li3 = Diff(li1, li2)print(li3) |
- Output :
[10, 20, 30, 15]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
Recommended Posts:
- Python | Zipping two lists of lists
- Python | Program to count number of lists in a list of lists
- Python - Convert Lists into Similar key value lists
- Python | Difference of two lists including duplicates
- Creating a sorted merged list of two unsorted lists in Python
- Python | Intersection of two lists
- Python | Union of two or more Lists
- Python | Check if two lists have at-least one element common
- Python | Check whether two lists are circularly identical
- Python | Print all the common elements of two lists
- Python | Split the Even and Odd elements into two different lists
- Python | Find missing and additional values in two lists
- Python | Average of two lists
- Python | Check if two lists are identical
- Python | Convert two lists into a dictionary
- Python | Combining two sorted lists
- Python | Merge two lists into list of tuples
- Python | Concatenate two lists element-wise
- Python | Integrity Sorting in two lists
- Python | Dividing two lists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

