Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if two lists are identical in Python
Next article icon

Check if two given matrices are identical - Python

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we often need to check whether two given matrices are identical. Two matrices are considered identical if they have the same number of rows and columns and the corresponding elements in each matrix are equal. Let's explore various methods to compare two matrices and check if they are identical.

Using equality operator (==)

equality operator can be used to directly compare two matrices. Python lists support element-wise comparison, so this method is simple and efficient.

Python
# Input matrices m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[1, 2, 3], [4, 5, 6]]  # Check if matrices are identical res = m1 == m2 print(res)   

Output
True 

Explanation:

  • The equality operator compares the two matrices element by element.
  • If all corresponding elements in both matrices are equal, it returns True.
  • This method is simple and efficient for smaller matrices.

Let's explore some more methods and see how we can check if two given matrices are identical.

Table of Content

  • Using a loop to compare elements
  • Using zip() function
  • Using numpy for large matrices

Using zip()

zip() function can be used to pair up the rows of both matrices and then compare each pair.

Python
m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[1, 2, 3], [4, 5, 6]]  # Check if matrices are identical using zip res = all(r1 == r2 for r1, r2 in zip(m1, m2)) print(res)   

Output
True 

Explanation:

  • zip() function pairs up the corresponding rows from both matrices.
  • all() function checks if all the pairs of rows are equal.
  • This method uses Python's built-in functions for clean and efficient code.

Using for loop

We can also compare two matrices manually using nested loops. This method iterates over each element and checks if they are equal.

Python
m1 = [[1, 2, 3], [4, 5, 6]] m2 = [[1, 2, 3], [4, 5, 6]]  # Initialize result as True res = True  # Check if matrices have the same dimensions and elements for i in range(len(m1)):     for j in range(len(m1[i])):         if m1[i][j] != m2[i][j]:             res = False             break     if not res:         break print(res)  

Output
True 

Explanation:

  • We use nested loops to iterate through each element in both matrices.
  • If any element does not match, the result is set to False.
  • This method allows for a manual check of matrix equality and is useful when we need more control over the comparison process.

Using numpy for large matrices

When working with large matrices, the numpy library offers a very efficient way to compare matrices using the numpy.array_equal() function.

Python
import numpy as np  # Input matrices m1 = np.array([[1, 2, 3], [4, 5, 6]]) m2 = np.array([[1, 2, 3], [4, 5, 6]])  # Check if matrices are identical res = np.array_equal(m1, m2) print(res)  

Output
True 

Explanation:

  • We convert the matrices to numpy arrays and use the array_equal() function to check if they are identical.
  • This method works well for large matrices, as numpy optimizes such operations.

Next Article
Check if two lists are identical in Python

S

Shashank Mishra
Improve
Article Tags :
  • Matrix
  • Python
  • DSA
  • python-list
  • Python list-programs
Practice Tags :
  • Matrix
  • python
  • python-list

Similar Reads

  • Check if two given matrices are identical - Python
    In Python, we often need to check whether two given matrices are identical. Two matrices are considered identical if they have the same number of rows and columns and the corresponding elements in each matrix are equal. Let's explore various methods to compare two matrices and check if they are iden
    3 min read
  • Check if two lists are identical in Python
    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 ide
    2 min read
  • Check if a given matrix is Hankel or not
    Given a matrix m[][] of size n x n. The task is to check whether given matrix is Hankel Matrix or not.In linear algebra, a Hankel matrix (or catalecticant matrix), named after Hermann Hankel, is a square matrix in which each ascending skew-diagonal from left to right is constant. Examples: Input: n
    7 min read
  • Python | Check if list is Matrix
    Sometimes, while working with Python lists, we can have a problem in which we need to check for a Matrix. This type of problem can have a possible application in Data Science domain due to extensive usage of Matrix. Let's discuss a technique and shorthand which can be used to perform this task.Metho
    3 min read
  • Check Whether Two Lists are Circularly Identical
    We are given two lists of elements, and the task is to check if one list is a circular rotation of the other. For example, the lists [10, 10, 10, 0, 0] and [10, 10, 10, 0, 0] are circularly identical because the second list can be obtained by rotating the first list. Let's discuss various ways to pe
    3 min read
  • Program to check Identity Matrix
    Given a square matrix mat[][] of order n*n, the task is to check if it is an Identity Matrix. Identity Matrix: A square matrix is said to be an identity matrix if the elements of main diagonal are one and all other elements are zero. The identity Matrix is also known as the Unit Matrix. Examples: In
    5 min read
  • Check if two elements of a matrix are on the same diagonal or not
    Given a matrix mat[][], and two integers X and Y, the task is to check if X and Y are on the same diagonal of the given matrix or not. Examples: Input: mat[][]= {{1, 2}. {3, 4}}, X = 1, Y = 4 Output: YesExplanation:Both X and Y lie on the same diagonal. Input: mat[][]= {{1, 2}. {3, 4}}, X = 2, Y = 4
    7 min read
  • Python - Check if list contains all unique elements
    To check if a list contains all unique elements in Python, we can compare the length of the list with the length of a set created from the list. A set automatically removes duplicates, so if the lengths match, the list contains all unique elements. Python provides several ways to check if all elemen
    2 min read
  • Check if two arrays are equal or not
    Given two arrays, a and b of equal length. The task is to determine if the given arrays are equal or not. Two arrays are considered equal if: Both arrays contain the same set of elements.The arrangements (or permutations) of elements may be different.If there are repeated elements, the counts of eac
    6 min read
  • Check if a List is Sorted or not - Python
    We are given a list of numbers and our task is to check whether the list is sorted in increasing or decreasing order. For example, if the input is [1, 2, 3, 4], the output should be True, but for [3, 1, 2], it should be False. Using all()all() function checks if every pair of consecutive elements in
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences