Thursday, December 26, 2024
Google search engine
HomeLanguagesPython Find Differences Between Two Lists

Python Find Differences Between Two Lists

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

  1. Python Print List Elements in Different Way
  2. How to Input List From User in Python
  3. Python Add and Remove Elements From List
  4. Python: Add/Insert Element at Specified Index in List
  5. Python Program to Remove ith/Nth Occurrence of Given Word in List
  6. Python Program to Sort List in Ascending and Descending Order
  7. Python Programs to Split Even and Odd Numbers in Separate List
  8. Python Program to Create Two Lists with First Half and Second Half Elements of Given List
  9. Python Program to Swap Two Elements in a List
  10. Python Program to Reverse List
  11. How To Select Random Item From A List In Python
RELATED ARTICLES

Most Popular

Recent Comments