 Open in App
Not now

# Python List Equality | Program to check if two given matrices are identical

• Difficulty Level : Basic
• Last Updated : 29 Dec, 2022

We are given two square matrices of same order. Check if two given matrices are identical.

Examples:

```Input :     A = [ [1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]

B = [ [1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]

Output:    Matrices are identical```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We have existing solution for this problem please refer C Program to check if two given matrices are identical link. In python any iterable object is comparable so we can solve this problem quickly in python with the help of List Equality

Implementation:

## Python3

 `# Function to check if two given matrices are identical` `def` `identicalMatrices(A,B):` `    ``if` `A``=``=``B:``        ``print` `(``'Matrices are identical'``)``    ``else``:``        ``print` `(``'Matrices are not identical'``)` `# Driver program``if` `__name__ ``=``=` `"__main__"``:``    ``A ``=` `[ [``1``, ``1``, ``1``, ``1``],``        ``[``2``, ``2``, ``2``, ``2``],``        ``[``3``, ``3``, ``3``, ``3``],``        ``[``4``, ``4``, ``4``, ``4``]]` `    ``B ``=` `[ [``1``, ``1``, ``1``, ``1``],``        ``[``2``, ``2``, ``2``, ``2``],``        ``[``3``, ``3``, ``3``, ``3``],``        ``[``4``, ``4``, ``4``, ``4``]]``    ``identicalMatrices(A,B)`

Output

`Matrices are identical`

Another approach to solving this problem without using loops is to use the built-in function all. This function returns True if all elements in an iterable are True, and False otherwise.

We can use this function to check if all elements in the matrices are equal by first zipping the two matrices together, then using a list comprehension to check if each element in the zipped list is equal. We can then pass the resulting list to the all function to check if all elements are equal.

Here is an example of this approach:

## Python3

 `def` `identical_matrices(A, B):``    ``equal ``=` `all``([a ``=``=` `b ``for` `a, b ``in` `zip``(A, B)])``    ``if` `equal:``        ``print``(``"Matrices are identical"``)``    ``else``:``        ``print``(``"Matrices are not identical"``)` `A ``=` `[[``1``, ``1``, ``1``, ``1``], [``2``, ``2``, ``2``, ``2``], [``3``, ``3``, ``3``, ``3``], [``4``, ``4``, ``4``, ``4``]]``B ``=` `[[``1``, ``1``, ``1``, ``1``], [``2``, ``2``, ``2``, ``2``], [``3``, ``3``, ``3``, ``3``], [``4``, ``4``, ``4``, ``4``]]``identical_matrices(A, B)`

Output

`Matrices are identical`

My Personal Notes arrow_drop_up