TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python to Find Difference Between Two Lists
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python to Find Difference Between Two Lists

Last updated: Oct 29, 2023 5:23 pm
By Meenakshi Agarwal
Share
5 Min Read
Python to Find Difference Between Two Lists
Python to Find Difference Between Two Lists
SHARE

In this tutorial, we’ll discover two Pythonic ways to find the Difference Between Two Lists. One of the methods is using the Python Set. It first converts the lists into sets and then gets the unique part out of that.

Contents
Use set() to find the difference of two listsWithout set(), using nested loopsWithout set(), using list comprehension

Other non-set methods compare two lists element by element and collect the unique ones. We can implement these by using nested for loops and with the list comprehension.

By the way, if you are not aware of the sets in Python, then follow the below tutorial. It would quickly introduce you to how Python implements the mathematical form of Set.

Python Set

Pythonic Ways to Find the Difference Between Two Lists

Python Set seems to be the most obvious choice to identify the common as well as the difference of two lists. So, we are going to explore it first and then will use nested loops and list comprehension.

Before we move on to the solution part, let’s define the test parameters, i.e., the two lists which we have to find the difference.

# Test Input
list_a = [11, 16, 21, 26, 31, 36, 41]
list_b = [26, 41, 36]

And we want our solution to provide the following output:

# Expected Result
# list_out = list_a - list_b
list_out = [11, 21, 31, 16]

Let’s start to create a program to find the difference between two lists, first using sets.

Use set() to find the difference of two lists

In this approach, we’ll first derive two SETs (say set1 and set2) from the LISTs (say list1 and list2) by passing them to set() function. After that, we’ll perform the set difference operation. It will return those elements from list1 which don’t exist in the second.

Here is the sample Python program to get the difference of two lists.

"""
Desc:
 Using set() to find the difference between two lists in Python
"""

def list_diff(list1, list2): 
	return (list(set(list1) - set(list2))) 

# Test Input
list1 = [11, 16, 21, 26, 31, 36, 41] 
list2 = [26, 41, 36] 

# Run Test
print(list_diff(list1, list2)) 

After running this, you should see the following outcome:

[16, 11, 21, 31]

Without set(), using nested loops

In this method, we’ll use nested For Loop to compare each element of the first list with the second. And while traversing, we’ll be appending every non-matching item to a new (and empty) list.

The new list would finally include the difference between the two given sequences. Below is the sample program to demonstrate this approach.

"""
Desc:
 Nested loop to find the difference between two lists in Python
"""

def list_diff(list1, list2):
    out = []
    for ele in list1:
        if not ele in list2:
            out.append(ele)
    return out

# Test Input
list1 = [11, 16, 21, 26, 31, 36, 41] 
list2 = [26, 41, 36] 

# Run Test
print(list_diff(list1, list2)) 

After running the above program, you should see the following outcome:

[11, 16, 21, 31]

Without set(), using list comprehension

It is almost a similar technique that we used in the previous one. Here, we replaced the nested loops with the list comprehension syntax.

See the example below.

"""
Desc:
 List comprehension to find the difference between two lists in Python
"""

def list_diff(list1, list2):
    out = [item for item in list1 if not item in list2]
    return out

# Test Input
list1 = [11, 16, 21, 26, 31, 36, 41] 
list2 = [26, 41, 36] 

# Run Test
print(list_diff(list1, list2)) 

After running the above program, you should see the following outcome:

[11, 16, 21, 31]

We hope that after wrapping up this tutorial, you should know several ways to check two lists for the difference. However, you may practice more with examples to gain confidence.

Also, to learn Python from scratch to depth, do read our step by step Python tutorial.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article MySQL UPSERT is INSERT or UPDATE with Examples MySQL UPSERT | INSERT or UPDATE
Next Article MySQL FROM_UNIXTIME() Function with Examples MySQL FROM_UNIXTIME() Function

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x