Open In App

Check if two lists are identical in Python

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Our task is to check if two lists are identical or not. By "identical", we mean that the lists contain the same elements in the same order. The simplest way to check if two lists are identical using the equality operator (==).

Using Equality Operator (==)

The easiest way to check if two lists are identical is by using the equality operator (==). This method compares each element of both lists in the same order and return True if they match, otherwise False.

Python
a = [1, 2, 3]
b = [1, 2, 4]

res = a == b
print(res)

Output
False

Explanation: Since the last elements in a and b are different (3 vs 4), so the result is False.

Using a loop

In this approach, we first check if lists are of equal length. Then, we use a for loop to compare each element. If any element differs or the lengths do not match then the lists would not be identical. Otherwise, identical.

Python
a = [1, 2, 3]
b = [1, 2, 3]

flag = True

if len(a) != len(b):
  
    flag = False 
else:
  
    for i in range(len(a)):   
      
        if a[i] != b[i]:
            flag = False  
            break  

print(flag)

Output
True

Explanation:

  • len(a) != len(b): Checks if the lists have different lengths; if true, flag is set to False.
  • for i in range(len(a)): Loops through the elements of the lists.
  • a[i] != b[i]: Compares corresponding elements of the lists. If any mismatch is found, flag is set to False and the loop breaks.
  • print(flag): Outputs True if the lists are identical, otherwise False.

Using all() with zip()

Another effective way to check for identical lists is by using the all() function along with zip(). This method pairs elements from both lists and checks if all corresponding elements are equal. If any pair differs, all() returns False (means, lists are not identical).

Python
a = [5, 6, 7]
b = [5, 6, 7]

flag = all(x == y for x, y in zip(a, b))
print(flag)

Output
True

Explanation: The zip() function pairs each element from a and b and all() checks whether each pair matches. Since all pairs are identical then output is True.

Related Articles:


Next Article
Practice Tags :

Similar Reads