Compare Lists in Python

  1. Use the for Loop to Compare Lists in Python
  2. Use the set to Compare Lists in Python
  3. Use the collection.counter() Function to Compare Two Lists in Python

Lists are used to store multiple elements in a specific order in Python.

In this tutorial, we will learn how to compare two lists and find the elements that are equal.

Use the for Loop to Compare Lists in Python

The for loop can be used to iterate over the list and compare each element of one list with all the second list elements. With this method, we can find compare elements individually and find out the common elements.

The following code shows how to implement this.

l1 = [1,2,3]
l2 = [3,2,5]
for i in l1:
    for j in l2:
        if(i==j):
            print(i)
            break

Output:

2
3

Use the set to Compare Lists in Python

The Set is a collection of elements and is unordered. We can directly convert a list to a set using the set() function and compare them for equality.

For example,

l1 = [1, 2, 3, 4, 5]
l2 = [9, 8, 7, 6, 5]

if(set(l1) == set(l2)):
    print("Lists are equal")
else:
    print("Lists are not equal")

Output:

Lists are not equal

We can also find out the common elements between two lists using the & operator, which returns the intersection of two sets.

For example,

l1 = [1, 2, 3, 4, 5]
l2 = [9, 8, 7, 6, 5]
    
print("Common Elements", set(l1) & set(l2))

Output:

Common Elements {5}

Use the collection.counter() Function to Compare Two Lists in Python

The counter() function returns a dictionary that contains all the elements in the list and their frequency as key-value pairs. We can compare this dictionary to check for equality and more.

For example,

import collections
l1 = [1, 2, 3]
l2 = [3, 2, 1]

if(collections.Counter(l1)==collections.Counter(l2)):
    print("Equal")
else:
    print("Not Equal")

Output:

Equal
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Check Element Not in a List in Python
  • Write a List to a File With Python