Python | Difference between two lists
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:# Python code t get difference of two lists# Using set()defDiff(li1, li2):return(list(set(li1)-set(li2)))# Driver Codeli1=[10,15,20,25,30,35,40]li2=[25,40,35]print(Diff(li1, li2))chevron_rightfilter_noneOutput :
[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.# Python code t get difference of two lists# Not using set()defDiff(li1, li2):li_dif=[iforiinli1+li2ifinotinli1orinotinli2]returnli_dif# Driver Codeli1=[10,15,20,25,30,35,40]li2=[25,40,35]li3=Diff(li1, li2)print(li3)chevron_rightfilter_noneOutput :
[10, 20, 30, 15]
Recommended Posts:
- Python | Difference of two lists including duplicates
- Python | Program to count number of lists in a list of lists
- Python | Zipping two lists of lists
- Python set operations (union, intersection, difference and symmetric difference)
- Python | Union of Value Lists
- Python | Intersection of two lists
- Python | Dividing two lists
- Python | Using 2D arrays/lists the right way
- Python | Union of two or more Lists
- Python | All possible permutations of N lists
- Output of python program | Set 11(Lists)
- Python | Initializing multiple lists
- Python | Ways to concatenate two lists
- Python | Merge two lists alternatively
- Python | Split list into lists by particular value
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.



