Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to list the difference between two lists.
In Python, Lists are one of the built-in data types used for storing collections of data. Python lists are sequences of comma-separated items, enclosed in square brackets []. They are flexible, easy to manipulate and widely used in various applications.
In this article, we will explore different methods to find the difference between two lists. Python provides several built-in approaches for achieving this.
Using set.difference() Method
The Python set.difference() method returns a new set containing elements that are present in the first set but not in any other sets provided as arguments.
Syntax
set.difference(*others)
This method converts both lists to sets and finds elements only in the first set ?
Example
Here's how to find elements present in the first list but not in the second ?
x = [11, 2, 3, 22]
y = [22, 11]
result = list(set(x).difference(set(y)))
print("Elements in x but not in y:", result)
Elements in x but not in y: [2, 3]
Using List Comprehension
List comprehension provides a concise way to filter elements. We loop through the first list and keep only elements that don't exist in the second list.
Example
Finding the difference between two lists using list comprehension ?
x = ['ciaz', 'bmw', 'audi']
y = ['cruze', 'ciaz']
result = [item for item in x if item not in y]
print("Elements in x but not in y:", result)
Elements in x but not in y: ['bmw', 'audi']
Using set.symmetric_difference() Method
The Python set.symmetric_difference() method returns elements present in either of two sets but not in both sets.
Syntax
set.symmetric_difference(other)
This method finds elements unique to each list ?
Example
Finding elements that exist in either list but not in both ?
x = [11, 2, 32, 3]
y = [32, 11, 5]
result = list(set(x).symmetric_difference(set(y)))
print("Elements unique to each list:", result)
Elements unique to each list: [2, 3, 5]
Comparison of Methods
| Method | Returns | Best For |
|---|---|---|
set.difference() |
Elements only in first list | One-way difference |
| List comprehension | Elements only in first list | Preserving order |
set.symmetric_difference() |
Elements unique to each list | Two-way difference |
Conclusion
Use set.difference() for finding elements in one list but not another. Use list comprehension when you need to preserve the original order. Use set.symmetric_difference() to find elements unique to either list.
