Not the most efficient one, but by far the most obvious way to do it is:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}

if order is significant you can do it with list comprehensions like this:

>>> [i for i, j in zip(a, b) if i == j]
[5]

(only works for equal-sized lists, which order-significance implies).

Answer from SilentGhost on Stack Overflow
🌐
Miguendes
miguendes.me › python-compare-lists
The Best Ways to Compare Two Lists in Python
July 2, 2022 - Let's go! The easiest way to compare two lists for equality is to use the == operator. This comparison method works well for simple cases, but as we'll see later, it doesn't work with advanced comparisons.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-compare-two-lists-in-python
How to Compare Two Lists in Python | DigitalOcean
July 22, 2025 - When your goal is to find which elements are shared or which are unique between two lists, the most efficient and Pythonic approach is to use the set() function. It creates set objects using the given lists and then compares the sets for equality using the == operator.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Compare Lists in Python | note.nkmk.me
May 10, 2023 - Difference between the == and is operators in Python · print([1, 2, 3] == [True, 2.0, 3 + 0j]) # True · source: list_compare.py · != is the negation of ==. print([1, 2, 3] != [1, 2, 3]) # False print([1, 2, 3] != [3, 2, 1]) # True print([1, 2, 3] != [1, 2]) # True print([1, 2, 3] != [True, 2.0, 3 + 0j]) # False · source: list_compare.py · Note that is determines the identity of the objects. If the two lists point to the same object, it returns True.
🌐
STechies
stechies.com › compare-lists-python-using-set-cmp-function
How to Compare Two Lists in Python using set(), cmp() and difference() Functions
In this example, we first sort the list, so that element of the list is in the same order and then compare both the list with == operator · # Python 3 code # check if list are equal # using sort() & == operator # initializing list and convert into set object x = ['x1','rr','x3','y4'] y = ['x1','rr','rr','y4'] print ("List first: " + str(x)) print ("List second: " + str(y)) # sort list x and y x.sort() y.sort() # if lists are equal if x == y: print("First and Second list are Equal") # if lists are not equal else: print("First and Second list are Not Equal")
🌐
PythonForBeginners.com
pythonforbeginners.com › home › compare two lists in python
Compare two lists in Python - PythonForBeginners.com
October 22, 2021 - To compare two lists in python, we can use sets. A set in python only allows unique values in it. We can use this property of sets to find if two lists have the same elements or not.
🌐
TutorialsPoint
tutorialspoint.com › how-to-compare-two-lists-in-python
How to compare two lists in Python?
def compare_lists(list1, list2): if list1 == list2: return "Equal" else: return "Not equal" # Same elements, same order numbers1 = [1, 2, 3] numbers2 = [1, 2, 3] print("Same order:", compare_lists(numbers1, numbers2)) # Same elements, different ...
Find elsewhere
🌐
Centron
centron.de › startseite › how to compare two lists in python
Compare Two Lists in Python: A Comprehensive Guide
February 4, 2025 - You can use the set() function to create set objects using the given lists and then compare the sets for equality using the == operator. Note: Duplicate list items appear only once in a set.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-compare-two-lists-in-python
How to compare two lists in Python? - GeeksforGeeks
July 23, 2025 - Let’s explore other methods to compare two lists in Python. ... counter() function of the collections module is used to sort and store the list elements in the form of a dictionary which makes it easier to compare two lists. ... import collections a = [1, 2, 3, 4, 5] b = [5, 4, 3, 2, 1] # Counter creates a dictionary-like object res = collections.Counter(a) == collections.Counter(b) print(res)
Top answer
1 of 4
16

I might do something like:

set1 = set((x.id,x.name,...) for x in list1)
difference = [ x for x in list2 if (x.id,x.name,...) not in set1 ]

where ... is additional (hashable) attibutes of the instance -- You need to include enough of them to make it unique.

This takes your O(N*M) algorithm and turns it into an O(max(N,M)) algorithm.

2 of 4
9

Just a thought...

class Foo(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return '({},{})'.format(self.id, self.name)

list1 = [Foo(1,'a'),Foo(1,'b'),Foo(2,'b'),Foo(3,'c'),]
list2 = [Foo(1,'a'),Foo(2,'c'),Foo(2,'b'),Foo(4,'c'),]

So ordinarily this does not work:

print(set(list1)-set(list2))
# set([(1,b), (2,b), (3,c), (1,a)])

But you could teach Foo what it means for two instances to be equal:

def __hash__(self):
    return hash((self.id, self.name))

def __eq__(self, other):
    try:
        return (self.id, self.name) == (other.id, other.name)
    except AttributeError:
        return NotImplemented

Foo.__hash__ = __hash__
Foo.__eq__ = __eq__

And now:

print(set(list1)-set(list2))
# set([(3,c), (1,b)])

Of course, it is more likely that you can define __hash__ and __eq__ on Foo at class-definition time, instead of needing to monkey-patch it later:

class Foo(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __repr__(self):
        return '({},{})'.format(self.id, self.name)

    def __hash__(self):
        return hash((self.id, self.name))

    def __eq__(self, other):
        try:
            return (self.id, self.name) == (other.id, other.name)
        except AttributeError:
            return NotImplemented

And just to satisfy my own curiosity, here is a benchmark:

In [34]: list1 = [Foo(1,'a'),Foo(1,'b'),Foo(2,'b'),Foo(3,'c')]*10000

In [35]: list2 = [Foo(1,'a'),Foo(2,'c'),Foo(2,'b'),Foo(4,'c')]*10000
In [40]: %timeit set1 = set((x.id,x.name) for x in list1); [x for x in list2 if (x.id,x.name) not in set1 ]
100 loops, best of 3: 15.3 ms per loop

In [41]: %timeit set1 = set(list1); [x for x in list2 if x not in set1]
10 loops, best of 3: 33.2 ms per loop

So @mgilson's method is faster, though defining __hash__ and __eq__ in Foo leads to more readable code.

Top answer
1 of 2
14

The problem with this is that, for each element in list A, you're checking all of the elements in list B. So, if the lengths of your lists are N and M, that's N*M comparisons.

If you make a set of the usernames from list B, then you can just use the in operator on it—which is not only simpler, it's instantaneous, instead of having to check all of the values one by one. So, you only need N lookups instead of N*M.

So:

b_names = {record.username for record in List_B}
for record_a in List_A:
    if record_a.username in b_names:
        print "Duplicate username: {0}".format(record_a.username)

Or, even simpler, use set intersection:

a_names = {record.username for record in List_A}
b_names = {record.username for record in List_B}
for name in a_names & b_names:
    print "Duplicate username: {0}".format(name)

And really, you don't need both of them to be sets, you can make one a set and the other just an iterator, using a generator expression:

a_names = {record.username for record in List_A}
b_names = (record.username for record in List_B)
for name in a_names.intersection(b_names):
    print "Duplicate username: {0}".format(name)

One of these may be a little faster than the others, but they'll all be in the same ballpark—and, more importantly, they're all linear instead of quadratic. So, I'd suggest using whichever one makes the most sense to you.

If you just need to know whether there are duplicates rather than get a list of them, or just need to get one of the duplicates arbitrarily rather than all of them, you can speed it up by "short-circuiting" early—e.g., adding a break after the print in the first one, or using isdisjoint instead of intersection in the last one.

2 of 2
-1

You could try something like:

for rec_a, rec_b in zip(List_A, List_B):
    if rec_a == rec_b:
        print "Duplicate username: {0}".format(rec_a.username)
🌐
Scaler
scaler.com › home › topics › python list comparison
Python List Comparison - Scaler Topics
May 4, 2023 - This return value can be one of three things: 1, 0 or -1. For instance, if l1 and l2 are two lists, then value 1 is returned if l1 (list 1) is greater than l2 (or list2). If l1 is smaller than l2, the value -1 is returned; otherwise, the value 0 is returned. Let us now look at an example. Code : ... The map() method in Python takes as inputs a function and a Python iterable object (list, tuple, string, etc.) and produces a map object.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-difference-two-lists
Difference between Two Lists in Python - GeeksforGeeks
November 27, 2025 - Below are several ways to get the difference between two lists in Python. This method finds the difference by converting both lists into sets and subtracting them. The - operator removes every element from the first set that also exists in the second set, giving only the unique elements from the first list. ... This method finds the difference by comparing how many times each element appears in both lists.
🌐
Medium
medium.com › @jesscsommer › comparing-objects-by-attribute-in-python-354d0590f8ea
Comparing objects by attribute in Python
June 9, 2023 - Sets will make our lives easier should we want to compare two lists of puzzles, so we’ll also define a __hash__ method to make this possible. This is where we return a value that’s unique and constant through the object’s lifetime. Python recommends creating a tuple with the attributes relevant for the comparison, then returning its hash value.
🌐
Javatpoint
javatpoint.com › how-to-compare-two-lists-in-python
How to compare two lists in Python - Javatpoint
How to compare two lists in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, basics, data types, operators, etc.
🌐
Finxter
blog.finxter.com › home › learn python blog › the most pythonic way to compare two lists in python
The Most Pythonic Way to Compare Two Lists in Python - Be on the Right Side of Change
June 27, 2020 - Short answer: The most Pythonic way to compute the difference between two lists l1 and l2 is the list comprehension statement [x for x in l1 if x not in set(l2)]. This works even if you have duplicate list entries, it maintains the original ...
🌐
Ubiq BI
ubiq.co › home › how to compare two lists in python
How to Compare Two Lists in Python - Ubiq BI
February 12, 2026 - We use equality operator ‘==’ to compare the result of Counter objects for both lists. In this article, we have learnt several different ways to compare two lists. If your lists are small-medium size, then you can use set() constructor to convert them into set, since it offers many useful ...
🌐
Quora
quora.com › How-do-I-compare-two-lists-in-Python
How to compare two lists in Python - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.