Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Interchange Elements of First and Last in a Matrix Across Columns
A matrix is a two-dimensional array of numbers arranged in rows and columns. Python doesn't have a built-in matrix data type, but we can use nested lists or NumPy arrays to represent matrices.
In this tutorial, we'll learn how to interchange the first and last column elements in each row of a matrix using different approaches.
Input Output Scenarios
Let's understand the problem with examples. For a 3×3 matrix, we swap the first and last elements of each row ?
# Example 1: Square matrix
original = [
[1, 3, 4],
[4, 5, 6],
[7, 8, 3]
]
# After swapping first and last column elements
result = [
[4, 3, 1],
[6, 5, 4],
[3, 8, 7]
]
for row in original:
print(row)
[1, 3, 4] [4, 5, 6] [7, 8, 3]
For matrices with unequal row lengths ?
# Example 2: Non-square matrix
matrix = [
['a', 'b'],
['c', 'd', 'e'],
['f', 'g', 'h', 'i']
]
for row in matrix:
print(row)
['a', 'b'] ['c', 'd', 'e'] ['f', 'g', 'h', 'i']
Method 1: Using Index Swapping
The simplest approach is to swap elements using temporary variables and positive/negative indexing ?
def swap_columns_index(matrix):
"""Swap first and last column elements using indexing"""
for row in matrix:
if len(row) > 1: # Only swap if row has more than 1 element
temp = row[0]
row[0] = row[-1]
row[-1] = temp
return matrix
def display_matrix(matrix):
"""Helper function to display matrix"""
for row in matrix:
print(row)
print()
# Test with square matrix
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Original matrix:")
display_matrix(matrix1)
swap_columns_index(matrix1)
print("After swapping:")
display_matrix(matrix1)
Original matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9] After swapping: [3, 2, 1] [6, 5, 4] [9, 8, 7]
Method 2: Using List Methods
We can use pop(), insert(), and append() methods to remove and add elements at specific positions ?
def swap_columns_methods(matrix):
"""Swap using pop(), insert(), and append() methods"""
for row in matrix:
if len(row) > 1:
# Store first and last elements
first_element = row[0]
last_element = row[-1]
# Remove first and last elements
row.pop(0) # Remove first element
row.pop() # Remove last element
# Insert in swapped positions
row.insert(0, last_element) # Insert last at beginning
row.append(first_element) # Append first at end
return matrix
# Test with non-square matrix
matrix2 = [['a', 'b'], ['c', 'd', 'e'], ['f', 'g', 'h', 'i']]
print("Original matrix:")
display_matrix(matrix2)
swap_columns_methods(matrix2)
print("After swapping:")
display_matrix(matrix2)
Original matrix: ['a', 'b'] ['c', 'd', 'e'] ['f', 'g', 'h', 'i'] After swapping: ['b', 'a'] ['e', 'd', 'c'] ['i', 'g', 'h', 'f']
Method 3: Using Python's Tuple Swapping
Python allows elegant swapping using tuple unpacking ?
def swap_columns_tuple(matrix):
"""Swap using Python's tuple unpacking"""
for row in matrix:
if len(row) > 1:
row[0], row[-1] = row[-1], row[0]
return matrix
# Test with mixed data types
matrix3 = [[1, 'x', 3], ['a', 'b', 'c'], [10, 20, 30]]
print("Original matrix:")
display_matrix(matrix3)
swap_columns_tuple(matrix3)
print("After swapping:")
display_matrix(matrix3)
Original matrix: [1, 'x', 3] ['a', 'b', 'c'] [10, 20, 30] After swapping: [3, 'x', 1] ['c', 'b', 'a'] [30, 20, 10]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Index Swapping | Good | Fast | Learning purposes |
| List Methods | Verbose | Slower | Understanding list operations |
| Tuple Swapping | Excellent | Fast | Production code |
Conclusion
Use tuple swapping (row[0], row[-1] = row[-1], row[0]) for clean, efficient code. All methods work with both square and non-square matrices by checking row lengths before swapping.
