π‘ Problem Formulation: Rotating a list of lists (or matrix) in Python refers to the process of shifting the rows to become columns and vice versa, typically in a 90-degree turn fashion. For instance, given an input list [[1,2],[3,4]]
, the desired output after rotation might be [[3,1],[4,2]]
. This article demonstrates five effective methods to achieve this task, catering to both newcomers and seasoned Python developers.
Method 1: List Comprehension with zip
One straightforward way to rotate a matrix is by using the built-in zip
function combined with list comprehension. This technique unpacks the original lists as arguments to zip
which pairs elements with the same index, then converts the zipped object back into a list of lists.
Here’s an example:
matrix = [[1,2],[3,4]] rotated_matrix = [list(x) for x in zip(*matrix[::-1])] print(rotated_matrix)
Output:
[[3,1],[4,2]]
This code snippet reverses the original list of lists and then uses zip(*matrix[::-1])
to pair items with identical indexes. The use of list comprehension and list
constructor ensures the rotated structure is a list of lists.
Method 2: NumPy Rotation
If you’re working with numerical data and performance is critical, NumPy’s rot90()
function is optimal for rotating matrices. Here we leverage NumPy’s array structure and efficient computation.
Here’s an example:
import numpy as np matrix = np.array([[1,2],[3,4]]) rotated_matrix = np.rot90(matrix) print(rotated_matrix)
Output:
[[2 4] [1 3]]
This snippet first converts the list of lists into a NumPy array. Then, np.rot90(matrix)
is called to rotate the array counterclockwise. NumPy handles the rotation with high efficiency, making it ideal for large matrices.
Method 3: Using a Custom Function
For those who prefer a more educational approach without external modules, a custom function to perform the rotation can be written. This is a good exercise in understanding the mechanics of list rotation.
Here’s an example:
def rotate_matrix(matrix): return [list(i) for i in zip(*matrix[::-1])] matrix = [[1,2],[3,4]] rotated_matrix = rotate_matrix(matrix) print(rotated_matrix)
Output:
[[3,1],[4,2]]
This snippet defines a function rotate_matrix()
that encapsulates the list comprehension and zip
method described in Method 1. This approach promotes code reusability and makes the rotation logic more modular.
Method 4: List Comprehension with Slicing
Another list comprehension method involves using slicing to rotate the matrix. By adjusting the indices within the list comprehension, one can directly reorder the elements to achieve rotation.
Here’s an example:
matrix = [[1,2],[3,4]] rotated_matrix = [ [row[i] for row in matrix[::-1]] for i in range(len(matrix[0])) ] print(rotated_matrix)
Output:
[[3,1],[4,2]]
In this code snippet, the outer list comprehension iterates over the indices while the inner list comprehension reverses the matrix and selects the elements based on the current index. It’s a clear method but might be less intuitive than using zip
.
Bonus One-Liner Method 5: Using map
and zip
The functional map
function in combination with zip
can provide a succinct one-liner for matrix rotation. This is ideal for those who appreciate concise expression in Python.
Here’s an example:
matrix = [[1,2],[3,4]] rotated_matrix = list(map(list, zip(*reversed(matrix)))) print(rotated_matrix)
Output:
[[3,1],[4,2]]
This one-liner uses reversed(matrix)
for reversing the list of lists, zip
for transposition, and map(list, ...)
to convert tuples back into lists. Finally, the outer list constructor turns the map object into a list of lists.
Summary/Discussion
- Method 1: List Comprehension with
zip
. Strengths: Simple, Pythonic, and no external libraries required. Weaknesses: Less performant with very large matrices. - Method 2: NumPy Rotation. Strengths: Highly efficient, especially on large matrices. Weaknesses: Requires NumPy, which may be an unnecessary dependency for small projects or simple tasks.
- Method 3: Using a Custom Function. Strengths: Educational value, promotes understanding of the algorithm. Weaknesses: Essentially a repackaged version of Method 1, no performance benefits.
- Method 4: List Comprehension with Slicing. Strengths: Direct control over the rotation process. Weaknesses: Slightly more complex and less readable for beginners.
- Method 5: Using
map
andzip
. Strengths: Concise one-liner, functional approach. Weaknesses: May sacrifice some readability for brevity.