# Python Program to Reverse Every Kth row in a Matrix

Given a Matrix, the task is to write a python program to reverse every Kth row. Where K is some span value.

```Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4
Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]
Explanation : Every 4th row is reversed.```
```Input : test_list = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 2
Output : [[5, 3, 2], [3, 6, 8], [3, 5, 2], [6, 3], [3, 7, 4], [9, 2]]
Explanation : Every 2nd row is reversed. ```

Method 1 : Using reversed() and loop

In this, we iterate for each row, and if the Kth row is found, reversal of it is performed using reverse().

Example:

## Python3

 `# Python3 code to demonstrate working of` `# Reverse Kth rows in Matrix` `# Using reversed() + loop`   `# initializing list` `test_list ``=` `[[``5``, ``3``, ``2``], [``8``, ``6``, ``3``], [``3``, ``5``, ``2``],` `             ``[``3``, ``6``], [``3``, ``7``, ``4``], [``2``, ``9``]]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# initializing K` `K ``=` `3`   `res ``=` `[]` `for` `idx, ele ``in` `enumerate``(test_list):`   `    ``# checking for K multiple` `    ``if` `(idx ``+` `1``) ``%` `K ``=``=` `0``:`   `        ``# reversing using reversed` `        ``res.append(``list``(``reversed``(ele)))` `    ``else``:` `        ``res.append(ele)`   `# printing result` `print``(``"After reversing every Kth row: "` `+` `str``(res))`

Output

```The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]```

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2: Using Slicing and list comprehension

In this, the task of reversing is performed using string slice, and list comprehension is used as shorthand to perform task of iteration.

Example:

## Python3

 `# Python3 code to demonstrate working of` `# Reverse Kth rows in Matrix` `# Using Slicing + list comprehension`   `# initializing list` `test_list ``=` `[[``5``, ``3``, ``2``], [``8``, ``6``, ``3``], [``3``, ``5``, ``2``],` `             ``[``3``, ``6``], [``3``, ``7``, ``4``], [``2``, ``9``]]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# initializing K` `K ``=` `3`   `# using enumerate() to get index and elements.` `# list comprehension to perform of iteration` `res ``=` `[ele[::``-``1``] ``if` `(idx ``+` `1``) ``%` `K ``=``=` `0` `else` `ele ``for` `idx,` `       ``ele ``in` `enumerate``(test_list)]`   `# printing result` `print``(``"After reversing every Kth row: "` `+` `str``(res))`

Time Complexity: O(n)

Space Complexity: O(n)

Method 3 : Using index() and reverse() methods

## Python3

 `# Python3 code to demonstrate working of` `# Reverse Kth rows in Matrix`   `# initializing list` `test_list ``=` `[[``5``, ``3``, ``2``], [``8``, ``6``, ``3``], [``3``, ``5``, ``2``],` `            ``[``3``, ``6``], [``3``, ``7``, ``4``], [``2``, ``9``]]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# initializing K` `K ``=` `3`   `res ``=` `[]` `for` `i ``in` `test_list:` `    ``if``(test_list.index(i)``=``=``K``-``1``):` `        ``i.reverse()` `        ``res.append(i)` `    ``else``:` `        ``res.append(i)` `# printing result` `print``(``"After reversing every Kth row: "` `+` `str``(res))`

Output

```The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [2, 9]]```

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using range() function

## Python3

 `# Python3 code to demonstrate working of` `# Reverse Kth rows in Matrix`   `# initializing list` `test_list ``=` `[[``5``, ``3``, ``2``], [``8``, ``6``, ``3``], [``3``, ``5``, ``2``],` `             ``[``3``, ``6``], [``3``, ``7``, ``4``], [``2``, ``9``]]`   `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))`   `# initializing K` `K ``=` `3`   `for` `i ``in` `range``(K``-``1``, ``len``(test_list), K):` `    ``test_list[i] ``=` `test_list[i][::``-``1``]` `# printing result` `print``(``"After reversing every Kth row: "` `+` `str``(test_list))`

Output

```The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]```

Time complexity: O(n), where n is the length of the test_list. The range() function takes O(n) time
Auxiliary Space: O(n), extra space of size n is required

Method #5: Using itertools and islice() method

1. Define the input matrix test_list and the value of K, which indicates the frequency of row reversal.
2. Initialize a loop that starts from the Kth row and iterates through the matrix with a step of K.
Within the loop, use the reversed() function to reverse the order of elements in the current Kth row. This creates a reversed iterator object that points to the original list, so no additional memory is used to store the reversed row.
3. Use the islice() function from the itertools module to limit the length of the reversed iterator to the original length of the row. This is necessary because reversed() returns a reversed iterator that extends beyond the original length of the list, so we need to truncate the iterator to prevent it from including extra elements.
4. Convert the truncated reversed iterator object to a list object using the list() function, and replace the original Kth row with the reversed list.
5. After completing the loop, the input matrix will have every Kth row reversed. Print the modified matrix to verify the result.

## Python3

 `from` `itertools ``import` `islice` `test_list ``=` `[[``5``, ``3``, ``2``], [``8``, ``6``, ``3``], [``3``, ``5``, ``2``], [``3``, ``6``], [``3``, ``7``, ``4``], [``2``, ``9``]]` `# printing original list` `print``(``"The original list is : "` `+` `str``(test_list))` `K ``=` `3` `for` `i ``in` `range``(K``-``1``, ``len``(test_list), K):` `    ``test_list[i] ``=` `list``(islice(``reversed``(test_list[i]), ``len``(test_list[i])))`   `# printing result` `print``(``"After reversing every Kth row: "` `+` `str``(test_list))` `#This code is contributed by Rayudu.`

Output

```The original list is : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]]
After reversing every Kth row: [[5, 3, 2], [8, 6, 3], [2, 5, 3], [3, 6], [3, 7, 4], [9, 2]]```

Time complexity : O(N*K), where N is the number of rows in the matrix and K is the frequency of row reversal. This is because the code iterates over each Kth row and reverses the order of its elements using reversed() and islice(), which takes O(K) time.
Auxiliary Space: O(N*K), as the matrix is modified in place and no additional data structures are created. The islice() function returns an iterator that lazily evaluates the reversed list elements, so it doesn’t create a new list object in memory.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next