Matrix Operations: Row Swapping

PythonPythonBeginner
Practice Now

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.

  1. Open the matrix.py file in your code editor.

  2. Locate the swap_rows function in the file. This function is responsible for swapping the rows in the matrix.

  3. The swap_rows function 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.
  4. Inside the swap_rows function, 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 matrix list.

  5. After swapping the rows, you need to print the matrix. You can do this by using a for loop 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.

  6. Save the matrix.py file.

Test the Matrix Operations

  1. Open a terminal or command prompt and navigate to the directory containing the matrix.py file.

  2. Run the following command to execute the matrix.py file:

    python3 matrix.py
  3. The 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     10

    This 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.

âœĻ Check Solution and Practice

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like