Python | Remove last element from each row in Matrix

Python | Remove last element from each row in Matrix

In this tutorial, we'll see how to remove the last element from each row in a matrix (2D list).

1. Understanding the Problem

Given a matrix:

matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] 

Our goal is to remove the last element from each row, resulting in:

[ [1, 2, 3], [5, 6, 7], [9, 10, 11] ] 

2. Using List Comprehension

List comprehension provides a concise way to create lists. We can use this approach to iterate over each row of the matrix and remove its last element:

result = [row[:-1] for row in matrix] print(result) 

3. Using a Loop

If you prefer a more explicit approach, you can use a loop:

result = [] for row in matrix: result.append(row[:-1]) print(result) 

4. Wrapping in a Function

To organize our solution and make it more reusable, we can wrap it in a function:

def remove_last_from_matrix(mat): return [row[:-1] for row in mat] # Test the function matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] print(remove_last_from_matrix(matrix)) 

5. Conclusion

Both the methods will provide the expected result:

[ [1, 2, 3], [5, 6, 7], [9, 10, 11] ] 
  • List Comprehension: Provides a Pythonic one-liner to process each row in the matrix.

  • Loop: Offers a clear, step-by-step approach to iterate over the matrix and modify its rows.

In this tutorial, we leveraged simple list slicing techniques to effectively process rows in a matrix. Whether using list comprehension or loops, Python makes it straightforward to manipulate 2D lists.


More Tags

nserror subview jose4j moment-timezone jquery android-signing repository-pattern callback gesture rhel

More Programming Guides

Other Guides

More Programming Examples