• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[6 Ways] Compare Two Lists in Python and Return Non-Match Elements

Aniruddha Chaudhari/77475/6
CodePython

List preserves the order of the elements in the list. When you compare the two lists using “==” operator, it returns True if all the elements in the lists are the same and in the same order.

list_a = [2, 4, 6, 8]
list_b = [2, 4, 6, 8]

print(list_a==list_b)

Output:

True

If you change the order of the elements in any of the list and then compare it with other, it returns False.

list_a = [2, 4, 6, 8]
list_b = [2, 8, 6, 4]

print(list_a==list_b)

Output:

False

Now we want to compare the two list irrespective of their order.

Compare Two Lists in Python

Table of Contents

  • 1. Using Membership Operator
  • 2. Using Set Method
  • 3. Using Sort Method
  • 4. Return Non-Matches Elements with For Loop
  • 5. Difference Between Two List
  • 6. Lambda Function To Return All Unmatched Elements

1. Using Membership Operator

We can compare the list by checking if each element in the one list present in another list.

def is_identical(list_a, list_b):
    if len(list_a) != len(list_b):
        return False
    for i in list_a:
        if i not in list_b:
            return False
    return True
       

list_a = [2, 4, 6, 8]
list_b = [2, 8, 6, 4]

if is_identical(list_a, list_b):
    print("Two lists are identical.")
else:
    print("Two lists are different.")

Output:

Two lists are identical.

You can read more about Python list and its various method.

This is a tedious job as we have to traverse through the complete list.

You have to take one element from the list ‘A’ and needs to search if the element present in list ‘B’.

As the list is not sorted by default, for each element, it will take O(n) time to search the element in another list.

So, the total complexity will be O(n^2).

This is good for learning and definitely not the standard way of writing the Python code.

Can we optimize this problem?

Basically we need to find out the solution to solve this problem without traversing the complete list.

There is way of doing this. We can use the Python inbuilt functions for comparing two lists.

Let’s see.

2. Using Set Method

To compare two lists, we are using the set method.

  • If the length of the two lists is different, the list can not be identical and return False.
  • Else, Convert both the lists into sets.
  • Compare these two sets. If the sets are equal, two given lists are the same. Otherwise, two lists are different.
def is_identical(list_a, list_b):
    if len(list_a) != len(list_b):
        return False
    if set(list_a) == set(list_b):
        return True
    else:
        return False
        

list_a = [2, 4, 6, 8]
list_b = [2, 8, 6, 4]

if is_identical(list_a, list_b):
    print("Two lists are identical.")
else:
    print("Two lists are different.")

Output:

Two lists are identical.

Drawback of using set() method:

The set() method removes all the duplicate elements in the list. If your list contains duplicate elements, this solution will not work for you.

Let’s see how you can take a rid of this problem to compare two lists in Python.

3. Using Sort Method

We can sort the two given list and then compare.

We have already learned about two ways of sorting the Python list in the previous tutorial. Let’s use that to find if the two lists are the same.

list_a = [2, 4, 6, 6]
list_b = [2, 6, 4, 6]

def is_identical(list_a, list_b):
    list_a.sort()
    list_b.sort()
    return list_a == list_b

if is_identical(list_a, list_b):
    print("Two lists are identical.")
else:
    print("Two lists are different.")

Output:

Two lists are identical.

This solution will work even if the lists have duplicate elements.

Now, we are increasing the scope of our problem. Instead of checking if the two lists are the same or not, we also want to find the non-match elements in the list.

4. Return Non-Matches Elements with For Loop

You can write a function to return all unmatched elements in the list using for loop.

def non_match_elements(list_a, list_b):
    non_match = []
    for i in list_a:
        if i not in list_b:
            non_match.append(i)
    return non_match
       

list_a = [2, 4, 6, 8, 10, 12]
list_b = [2, 4, 6, 8]

non_match = non_match_elements(list_a, list_b)
print("No match elements: ", non_match)

Output:

No match elements: [10, 12]

Instead of just for loop, you can use other looping mechanisms in Python.

You can also modify the above code to return the index of non-match elements in the list.

5. Difference Between Two List

We can perform the subtraction operation on set to find the extra elements in one list from another list.

def get_difference(list_a, list_b):
    return set(list_a)-set(list_b)

list_a = [2, 4, 6, 8, 10, 12]
list_b = [2, 4, 6, 8]

non_match = list(get_difference(list_a, list_b))
print("No match elements: ", non_match)

Output:

No match elements: [10, 12]

Now, let’s find the unmatched elements from both the list.

def get_difference(list_a, list_b):
    non_match_a  = set(list_a)-set(list_b)
    non_match_b  = set(list_b)-set(list_a)
    non_match = list(non_match_a) + list(non_match_b)
    return non_match

list_a = [2, 4, 6, 8, 10, 12]
list_b = [2, 4, 6, 8, 9, 13]

non_match = get_difference(list_b, list_a)
print("Non-match elements: ", non_match)

Output:

Non-match elements: [9, 13, 10, 12]

This will give you all the unmatched elements from both the lists.

Let’s make it more interesting with some of the Python advanced concepts.

6. Lambda Function To Return All Unmatched Elements

We can rewrite the above regular function using the lambda function to get all the non-matched elements in the lists.

l_func = lambda x, y: list((set(x)- set(y))) + list((set(y)- set(x))) 

list_a = [2, 4, 6, 8, 10, 12]
list_b = [2, 4, 6, 8, 9, 13]

non_match = l_func(list_a, list_b)

print("Non-match elements: ", non_match)

Output:

Non-match elements: [10, 12, 9, 13]

Python is interesting and you can find many ways of comparing two lists.

Use-cases

I was working on one of the projects where I’m calling REST API. After getting a web response form REST API, I have to validate all the HTTP header fields whether all the required attributes are present or not.

The easiest way is to keep the list of all the expected attributes and then compare it with the list of attributes getting from the REST API response. If the two lists are not the same, through an error telling “attribute missing.”

Similarly, you can find the many other use-cases where you need to compare two or more Python list to find unmatched elements..

Other List Related Tutorials for Practice:

  • Check if all the Elements in the List are Same
  • Find sum of all elements in the list
  • Sorting List of Tuples in Python

In this tutorial, we have learned different methods to compare two lists in Python and return non match elements. If you have any doubts or if you know any other way of comparing two lists, share it with me in the comment.

Happy Pythoning!

Python Interview Questions eBook

Pythonpython list
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Nandu
    July 26, 2020 at 9:20 pm
    def get_difference(list_a, list_b):
        non_match_a  = set(list_a)-set(list_b)
        non_match_b  = set(list_a)-set(list_b)
        non_match = list(non_match_a) + list(non_match_b)
        return non_match
     
    list_a = [2, 4, 6, 8, 10, 12]
    list_b = [2, 4, 6, 8, 9, 13]
     
    non_match = get_difference(list_b, list_a)
    print("Non-match elements: ", non_match)
    
    For this o/p is [9, 13, 9, 13] not [10, 12, 9, 13] 

    Reason :

    non_match_a  = set(list_a)-set(list_b)
    non_match_b  = set(list_a)-set(list_b)
    

    it should be

     
    non_match_a  = set(list_a)-set(list_b)
    non_match_b  = set(list_b)-set(list_a)
    
    • Reply
      Aniruddha Chaudhari
      July 28, 2020 at 9:13 am

      Thanks for the correction, Nandu. Addressed.

  • Reply
    Simon H.
    October 10, 2020 at 4:45 am

    [].sort() does not return anything (https://docs.python.org/3/library/stdtypes.html#list.sort)

    def is_identical(list_a, list_b):
        return list_a.sort() == list_b.sort()
    

    can be written as:

    def is_identical(list_a, list_b):
        return sorted(list_a) == sorted(list_b)
    

    or

    def is_identical(list_a, list_b):
        list_a.sort()
        list_b.sort()
        return list_a.sort() == list_b.sort()
        # the original of list_a, list_b are sorted now
    
    • Reply
      Aniruddha Chaudhari
      October 11, 2020 at 12:09 pm

      Thanks for the correction. Edited.

    • Reply
      Lea Joseph Puthumana
      May 10, 2021 at 3:43 pm

      I have a similar problem to solve. Can you help?

        first_set = set(map(tuple, coords))
             second_set = set(map(tuple, coords1))
             similar=first_set.intersection(second_set)
      
      print(first_set)
      print(second_set)
      print(similar)
      

      Here in this code, I found the exact same corners.

      eg. My first set is (133, 708), (281, 287), (140, 396), (285, 550)

      Second set is (295, 315), (213, 552), (181, 643), (255, 396), (282, 552)

      Difference of 1st set coordinates and second set coordinates if <=5

      ie, last set of first & the second set is printed as similar corners.

      while (282-285,552-550) = (3,0) .Here difference is (3,0) .

      Similar corners of first & second set are (285, 550) & (282, 55

  • Reply
    Chris
    February 16, 2021 at 4:32 am

    How do I take this one step further in complexity? For example, if list a = [ (date, code), (date code), (date, code)...]
    and b = [(date, code), (date, code), (date, code)...], and what I want to do is delete the pairs where the codes are the same but some of the dates in b greater than dates in a

    Thanks, sir!

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard