Introduction
In this project, you will learn how to perform matrix operations, specifically swapping rows in a 5x5 matrix. This project is designed to help you understand basic matrix manipulation and improve your programming skills.
👀 Preview
$ python3 matrix.py
1 2 3 4 5
21 22 23 24 25
11 12 13 14 15
16 17 18 19 20
6 7 8 9 10
🎯 Tasks
In this project, you will learn:
- How to swap the elements of two rows in a matrix
- How to print the matrix with the numbers left-aligned and occupying 5 positions
🏆 Achievements
After completing this project, you will be able to:
- Understand how to manipulate matrices in Python
- Implement row swapping in a matrix
- Format the output of a matrix to meet specific requirements
- Apply your problem-solving skills to complete a practical programming task
Swap Rows in the Matrix
In this step, you will learn how to swap the elements of the 2nd row and the 5th row of the matrix a.
Open the
matrix.pyfile in your code editor.Locate the
swap_rowsfunction in the file. This function is responsible for swapping the rows in the matrix.The
swap_rowsfunction takes three arguments:matrix: the 5x5 matrix represented as a list of lists.row1: the index of the first row to be swapped.row2: the index of the second row to be swapped.
Inside the
swap_rowsfunction, you need to implement the logic to swap the rows. You can do this by using the tuple unpacking assignment:matrix[row1], matrix[row2] = matrix[row2], matrix[row1]This line of code will swap the values of the two rows in the
matrixlist.After swapping the rows, you need to print the matrix. You can do this by using a
forloop to iterate over the rows and print each row with the numbers left-aligned and occupying 5 positions:for row in matrix: print(" ".join(f"{num:<5}" for num in row))This will print each row with the numbers left-aligned and occupying 5 positions.
Save the
matrix.pyfile.
Test the Matrix Operations
Open a terminal or command prompt and navigate to the directory containing the
matrix.pyfile.Run the following command to execute the
matrix.pyfile:python3 matrix.pyThe output should be:
1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20 6 7 8 9 10This output shows that the 2nd row (6, 7, 8, 9, 10) and the 5th row (21, 22, 23, 24, 25) have been swapped successfully.
Congratulations! You have completed the matrix operations project. You have learned how to swap rows in a 5x5 matrix and print the matrix with the numbers left-aligned and occupying 5 positions.
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.



