1. Introduction
In programming, it's common to encounter scenarios where you need to find the difference between two lists. This blog post will guide you through a Python program that accomplishes this task.
2. Program Overview
1. Define two lists.
2. Use set operations to find the difference between the two lists.
3. Display the differences.
3. Code Program
# Python program to find the difference between two lists
# Define two lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Find the difference between the two lists
difference1 = list(set(list1) - set(list2))
difference2 = list(set(list2) - set(list1))
# Combine the differences
combined_difference = difference1 + difference2
# Print the differences
print("Difference between list1 and list2:", combined_difference)
Output:
Difference between list1 and list2: [1, 2, 3, 6, 7, 8]
4. Step By Step Explanation
1. We begin by defining two lists, list1 and list2.
2. To find the items that are in list1 but not in list2, we convert both lists to sets and use the subtraction operation. We do the same to find items in list2 that aren't in list1.
3. We then combine the differences from both operations to get all distinct items.
4. Finally, we print out the combined difference. As observed in the output, the numbers 1, 2, and 3 are in list1 but not in list2, while 6, 7, and 8 are in list2 but not in list1.
Comments
Post a Comment
Leave Comment