Python – Convert Rear column of a Multi-sized Matrix

When working with multi-sized matrices (lists containing sublists of different lengths), you may need to extract the last element from each row. This can be accomplished using negative indexing with [-1] to access the rear column efficiently.

Extracting Rear Column Elements

Here's how to extract the last element from each sublist in a multi-sized matrix ?

# Multi-sized matrix with different row lengths
matrix = [[41, 65, 25], [45, 89], [12, 65, 75, 36, 58], [49, 12, 36, 98], [47, 69, 78]]

print("Original matrix:")
print(matrix)

# Extract rear column (last elements)
rear_column = []
for row in matrix:
    rear_column.append(row[-1])

print("\nRear column elements:")
print(rear_column)
Original matrix:
[[41, 65, 25], [45, 89], [12, 65, 75, 36, 58], [49, 12, 36, 98], [47, 69, 78]]

Rear column elements:
[25, 89, 58, 98, 78]

Using List Comprehension

A more concise approach using list comprehension ?

matrix = [[41, 65, 25], [45, 89], [12, 65, 75, 36, 58], [49, 12, 36, 98], [47, 69, 78]]

# Extract rear column using list comprehension
rear_column = [row[-1] for row in matrix]

print("Matrix:")
print(matrix)
print("\nRear column:")
print(rear_column)
print("\nSorted rear column:")
print(sorted(rear_column))
Matrix:
[[41, 65, 25], [45, 89], [12, 65, 75, 36, 58], [49, 12, 36, 98], [47, 69, 78]]

Rear column:
[25, 89, 58, 98, 78]

Sorted rear column:
[25, 58, 78, 89, 98]

How It Works

  • Negative indexing: row[-1] accesses the last element of each sublist

  • Iteration: Loop through each row in the matrix

  • Extraction: Collect the last elements into a new list

  • Flexibility: Works regardless of sublist length

Comparison

Method Readability Lines of Code Best For
For loop High 3-4 Complex operations
List comprehension Medium 1 Simple transformations

Conclusion

Use negative indexing [-1] to extract the rear column from multi-sized matrices. List comprehension provides a concise solution, while for loops offer better readability for complex operations.

Updated on: 2026-03-26T01:42:54+05:30

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements