Python | Program to find the differences of two lists

Python | Difference between two lists: In this tutorial, we will learn how to find the differences between two lists with the same type and the mixed type in Python. By IncludeHelp Last updated : June 22, 2023

Problem statement

Given two Python lists of integers, we have to find the differences i.e., the elements which do not exist in the second list.

Example

Consider the below example with sample input and output:

Input:
List1 = [10, 20, 30, 40, 50]
List2 = [10, 20, 30, 60, 70]

Output:
Different elements:
[40, 50]

Find the difference of two Python lists

The simplest approach to find the difference between two Python lists is that - the lists should be cast typed to the sets and then use minus (-) operator to get the difference i.e., the elements which are not in the second list.

Logic

To find the difference between two Python lists, you can use the set() method to explicitly convert lists into sets and then subtract the set converted lists, the result will be the elements which do not exist in the second.

Python program to find the difference between two lists of the same type

In this program, we have two lists having the same type of elements and finding the difference between the given lists.

# list1 - first list of the integers
# lists2 - second list of the integers
list1 = [10, 20, 30, 40, 50]
list2 = [10, 20, 30, 60, 70]

# printing lists 
print("list1:", list1)
print("list2:", list2)

# finding and printing differences 
# of the lists
print("Difference elements:")
print(list(set(list1) - set(list2)))

Example

list1: [10, 20, 30, 40, 50]
list2: [10, 20, 30, 60, 70]
Difference elements:
[40, 50]

Python program to find the difference between two lists of the mixed type

In this program we have two lists having the mixed type of elements and finding the difference between list1 and list2, also finding the difference between list2 and list1.

# list1 - first list with mixed type elements
# lists2 - second list with mixed type elements
list1 = ["Amit", "Shukla", 21, "New Delhi"]
list2 = ["Aman", "Shukla", 21, "Mumbai"]

# printing lists 
print("list1:", list1)
print("list2:", list2)

# finding and printing differences of 
# the lists
print("Elements not exists in list2:")
print(list(set(list1) - set(list2)))

print("Elements not exists in list1:")
print(list(set(list2) - set(list1)))

Example

list1: ['Amit', 'Shukla', 21, 'New Delhi']
list2: ['Aman', 'Shukla', 21, 'Mumbai']
Elements not exists in list2:
['Amit', 'New Delhi']
Elements not exists in list1:
['Aman', 'Mumbai']

Python List Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.