Skip to main content

py_mirror_matrix — Mirror a 2D Matrix Horizontally

Difficulty: easy

Write a function that mirrors a 2D matrix horizontally by reversing each row.

def mirror_matrix(matrix: list[list[int]]) -> list[list[int]]:

Examples

>>> mirror_matrix([[1, 2, 3], [4, 5, 6]])
[[3, 2, 1], [6, 5, 4]]

>>> mirror_matrix([[1, 2], [3, 4], [5, 6]])
[[2, 1], [4, 3], [6, 5]]

>>> mirror_matrix([[7]])
[[7]]

>>> mirror_matrix([[1, 2, 3, 4]])
[[4, 3, 2, 1]]

>>> mirror_matrix([[-1, -2], [-3, -4]])
[[-2, -1], [-4, -3]]

Solution

Download py_mirror_matrix.py
def mirror_matrix(matrix: list[list[int]]) -> list[list[int]]:
return [row[::-1] for row in matrix]

How It Works

Goal: Reverse every row of a 2D matrix, mirroring it across the vertical axis.

Approach: Use a list comprehension with Python's [::-1] slice trick to reverse each row.

Step by step:

  1. Iterate over every row of the matrix.
  2. For each row, row[::-1] produces a new list with elements in reverse order.
  3. Collect the reversed rows into a new outer list.

Key concept: Slice with a negative step — seq[::-1] returns a reversed copy without mutating the original.