Search code snippets, questions, articles...

Check if two lists are similar in Python

If you want to check whether two lists have the same items in Python, you can use one of the methods explained in this post.
list1 = [1, 2, 4, 3]
list2 = [1, 2, 3, 4]

if set(list1) == set(list2):
    print('Lists are similar')
else:
    print('Lists are not similar')
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
Lists are similar

We are using the set() function of Python to check whether two lists are identical or not. We will also explain more methods to check if the two lists contain the same items and values along with the same number of elements.

Check lists similarity using set() function

This is the easiest way to check where two given lists are identical or not in Python. The set() function takes the list as a parameter and we compare the lists using the == operator.

Syntax

set(List1) == set(List2)

Code Example

list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'b', 'c', 'd']

if set(list1) == set(list2):
  print('Lists are identical')
else:
  print('Lists are not identical')

Output

Lists are identical

Note that duplicate values are ignored when checking two list similarities using the set() function. If you want do not want to ignore duplicate items you can use the Counter() function of the collections module.

Using Counter() function from collections module

You can also use the Counter() function from the collections module to check whether two lists have the same items with a duplication check.

Syntax

Counter(list1) == Counter(list2)

Code Example

# Import Counter from collections
from collections import Counter

# Define the lists
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'b', 'c', 'd']

# Check if lists have same items at same positions
if Counter(list1) == Counter(list2):
  print('Identical')
else:
  print('Not identical')

Output

Identical
list1 = ['a', 'b', 'c', 'd']
list2 = ['a', 'b', 'd', 'c']

list1.sort()
list2.sort()

if list1 == list2:
  print('Lists are identical')
else:
  print('Lists are not identical')
We are using the sort() function here to check whether the two lists are the same or not. Firstly, we are sorting the lists using the sort() function and then comparing them using == operator.
Was this helpful?
0 Comments