Python | Flatten and Reverse Sort Matrix
Last Updated :
18 May, 2023
The flattening of list of list has been discussed many times, but sometimes, in addition to flattening, it is also required to get the string in reverse sorted manner. Let’s discuss certain ways in which this can be done.
Method #1: Using sorted() + reverse + list comprehension This idea is similar to flattening a list of list but in addition to it, we add a sorted function along with reverse as key, to reverse sort the returned flattened list done by list comprehension.
Python3
# Python3 code to demonstrate
# Flatten and Reverse Sort Matrix
# using sorted + list comprehension
# initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# printing original list of list
print("The original list : " + str(test_list))
# using sorted + list comprehension
# Flatten and Reverse Sort Matrix
res = sorted([j for i in test_list for j in i], reverse=True)
# print result
print("The reverse sorted and flattened list : " + str(res))
OutputThe original list : [[3, 5], [7, 3, 9], [1, 12]]
The reverse sorted and flattened list : [12, 9, 7, 5, 3, 3, 1]
Time Complexity: O(nlogn), where n is the length of the input list. This is because we’re using the sorted() + reverse + list comprehension which has a time complexity of O(nlogn) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2: Using itertools.chain() + sorted() + reverse The task that was done by list comprehension above can also be performed using the chain function that links elements of list and then sorted function does the task of sorting with the help of reverse for reverse sorting.
Python3
# Python3 code to demonstrate
# Flatten and Reverse Sort Matrix
# using itertools.chain() + sorted()
from itertools import chain
# initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# printing original list of list
print("The original list : " + str(test_list))
# using itertools.chain() + sorted()
# Flatten and Reverse Sort Matrix
res = sorted(chain(*test_list), reverse=True)
# print result
print("The reverse sorted and flattened list : " + str(res))
OutputThe original list : [[3, 5], [7, 3, 9], [1, 12]]
The reverse sorted and flattened list : [12, 9, 7, 5, 3, 3, 1]
Time Complexity: O(n*nlogn), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #3 : Using extend() and sort() methods
Python3
# Python3 code to demonstrate
# Flatten and Reverse Sort Matrix
# initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# printing original list of list
print("The original list : " + str(test_list))
# using sorted + list comprehension
# Flatten and Reverse Sort Matrix
res=[]
for i in test_list:
res.extend(i)
res.sort(reverse=True)
# print result
print("The reverse sorted and flattened list : " + str(res))
OutputThe original list : [[3, 5], [7, 3, 9], [1, 12]]
The reverse sorted and flattened list : [12, 9, 7, 5, 3, 3, 1]
Time Complexity: O(nlogn), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #4: Using recursion
Python3
def flatten(lst):
if not lst:
return []
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
#initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
#printing original list of list
print("The original list : " + str(test_list))
#using recursion
res = sorted(flatten(test_list), reverse=True)
#print result
print("The reverse sorted and flattened list : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list : [[3, 5], [7, 3, 9], [1, 12]]
The reverse sorted and flattened list : [12, 9, 7, 5, 3, 3, 1]
Time complexity : O(n log n)
Auxiliary Space: O(n)
Method 5: Use a stack and a while loop.
Step-by-step approach:
- Initialize an empty list flat_list to store the flattened list.
- Initialize a stack stack with the input list lst.
- Use a while loop to iterate through the stack until it becomes empty.
- Pop the last element from the stack and check if it is a list or not using isinstance() function. If it is a list, extend the stack with its elements in reverse order. If it is not a list, append it to flat_list.
- Use sorted() function with the reverse=True parameter to sort the flat_list in reverse order.
- Return the sorted flattened list.
Python3
def flatten(lst):
flat_list = []
stack = [lst]
while stack:
item = stack.pop()
if isinstance(item, list):
stack.extend(item[::-1])
else:
flat_list.append(item)
return sorted(flat_list, reverse=True)
# Initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# Printing original list of list
print("The original list : " + str(test_list))
# Using stack and while loop
res = flatten(test_list)
# Printing result
print("The reverse sorted and flattened list : " + str(res))
OutputThe original list : [[3, 5], [7, 3, 9], [1, 12]]
The reverse sorted and flattened list : [12, 9, 7, 5, 3, 3, 1]
Time complexity: O(n log n), where n is the total number of elements in the input list lst. The sorted() function takes O(n log n) time to sort the flattened list in reverse order.
Auxiliary space: O(n), where n is the total number of elements in the input list lst.
Method 6: Using a generator function and heapq
Python3
import heapq
def flatten_and_sort(lst):
def flatten_generator(lst):
for item in lst:
if isinstance(item, list):
yield from flatten_generator(item)
else:
yield item
flat_list = list(flatten_generator(lst))
heapq.heapify(flat_list)
sorted_list = []
while flat_list:
sorted_list.append(heapq.heappop(flat_list))
return sorted_list[::-1]
# Initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# Printing original list of list
print("The original list: " + str(test_list))
# Using generator function and heapq
res = flatten_and_sort(test_list)
# Printing result
print("The reverse sorted and flattened list: " + str(res))
OutputThe original list: [[3, 5], [7, 3, 9], [1, 12]]
The reverse sorted and flattened list: [12, 9, 7, 5, 3, 3, 1]
Time complexity is O(n + n + n log n) = O(n log n).
The auxiliary space is O(n) because we create a flat list to store all the elements before sorting them.
Similar Reads
Python - Reverse Row sort in Lists of List We are given a list of lists where each inner list represents a row and our task is to sort each row in descending order while keeping the overall structure intact. For example, given a = [[5, 2, 8], [9, 1, 4], [6, 7, 3]], after sorting each row in reverse order, the result will be [[8, 5, 2], [9, 4
3 min read
Python Program to Reverse Every Kth row in a Matrix We are given a matrix (a list of lists) and an integer K. Our task is to reverse every Kth row in the matrix. For example:Input : a = [[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]]Using reversed() and loopWe c
4 min read
Python Program to Print a given matrix in reverse spiral form Given a 2D array, print it in reverse spiral form. We have already discussed Print a given matrix in spiral form. This article discusses how to do the reverse printing. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1 Input: 1 2
5 min read
Python - Filter Sorted Rows Given a Matrix, extract rows that are sorted, either by ascending or descending. Input : test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]] Output : [[3, 6, 8, 10], [8, 5, 3, 2]] Explanation : Both lists are ordered, 1st ascending, second descending. Input : test_list = [[3, 6,
3 min read
Python | Sort Flatten list of list The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let's discuss certain ways in which this can be done. Method #1 : Using sorted() + list comprehension This idea is similar to flattening a l
7 min read
Python program to reverse a range in list Reversing a specific range within a list is a common task in Python programming that can be quite useful, when data needs to be rearranged. In this article, we will explore various approaches to reverse a given range within a list. We'll cover both simple and optimized methods. One of the simplest w
3 min read
Python - Ways to Flatten a 2D list We are given a 2D list we need to flatten that given list. For example, a = [[1, 2, 3], [4, 5], [6, 7, 8]] we need to flatten it so that the output becomes [1, 2, 3, 4, 5, 6, 7, 8].Using a Nested LoopA nested loop iterates over each sublist in the 2D list and then over each element in the sublist ap
3 min read
Take Matrix input from user in Python Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as 'rows' while the vertical entries are called as 'columns'. If a matrix has r number of rows and c number of columns then
5 min read
Python - Rear column in Multi-sized Matrix Given a Matrix with variable lengths rows, extract last column. Input : test_list = [[3, 4, 5], [7], [8, 4, 6], [10, 3]] Output : [5, 7, 6, 3] Explanation : Last elements of rows filtered. Input : test_list = [[3, 4, 5], [7], [8, 4, 6]] Output : [5, 7, 6] Explanation : Last elements of rows filtered
4 min read
Python Program to Sort the matrix row-wise and column-wise Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.Examples: Input : mat[][] = { {4, 1, 3}, {9, 6, 8}, {5, 2, 7} } Output : 1 3 4 2 5 7 6 8 9 Input : mat[][] = { {12, 7, 1, 8}, {20, 9, 11, 2}, {15, 4, 5, 13}, {3, 18, 10, 6} } Output : 1 5 8 12 2 6 10 15 3 7 11 18 4 9 13
4 min read