Python program to find the difference between two lists; In this python tutorial, we would love to share with you how to find the difference between two list in python using function and for loop.
Assume we have two lists and we have to get the difference by comparing the list of the first one and the second one.
For example:
Input: List1 = [10, 40, 30, 540, 600] List2 = [10, 20, 30, 60, 70] Output: Different elements: [540, 600]
Python Find Differences Between Two Lists
- Program to find difference of two lists in Python
- Python Program to find difference of two lists using For Loop
Program to find difference of two lists in Python
In this python program, we use the set() method to find the differences of the lists.
# list1 and list2 list1 = [200, 400, 300, 80, 90] list2 = [200, 400, 300, 70, 100] # print both the list print("list1:", list1) print("list2:", list2) # finding and printing differences of the lists print("Difference elements:") print(list (set(list1) - set (list2)))
After executing the program, the output will be:
list1: [200, 400, 300, 80, 90] list2: [200, 400, 300, 70, 100] Difference elements: [80, 90]
You have learned how to get the difference between two list in Python using set() method. Now you will learn how to find difference between two list in python using for loop with append() method.
You can see the following program to find difference of two lists using For Loop with append() method.
Python Program to find difference of two lists using For Loop
# list1 and list2 list1 = [200, 400, 300, 80, 90] list2 = [200, 400, 300, 70, 100] list_difference = [] for item in list1: if item not in list2: list_difference.append(item) print(list_difference)
After executing the program, the output will be:
[80, 90]
Recommended Python Programs
- Python Print List Elements in Different Way
- How to Input List From User in Python
- Python Add and Remove Elements From List
- Python: Add/Insert Element at Specified Index in List
- Python Program to Remove ith/Nth Occurrence of Given Word in List
- Python Program to Sort List in Ascending and Descending Order
- Python Programs to Split Even and Odd Numbers in Separate List
- Python Program to Create Two Lists with First Half and Second Half Elements of Given List
- Python Program to Swap Two Elements in a List
- Python Program to Reverse List
- How To Select Random Item From A List In Python