Open In App

Python | Sort Flatten list of list

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 list of list but in addition to it, we add a sorted function to sort the returned flattened list done by list comprehension. 

Python3




# Python3 code to demonstrate
# sort flatten list of list
# 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
# sort flatten list of list
res = sorted([j for i in test_list for j in i])
 
# print result
print("The sorted and flattened list : " + str(res))


Output

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]

Time Complexity: O(n log n) where n is the total number of elements in the nested list.
Auxiliary Space: O(n)
 

Method #2 : Using itertools.chain() + sorted() 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. 

Python3




# Python3 code to demonstrate
# sort flatten list of list
# 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()
# sort flatten list of list
res = sorted(chain(*test_list))
 
# print result
print("The sorted and flattened list : " + str(res))


Output

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]

The time complexity of the provided code is O(nlogn), where n is the total number of elements in the input list of lists. 

The auxiliary space complexity of the code is O(n), where n is the total number of elements in the input list of lists.

 Method #3: Using the sorted function and the sum function:

Here is another approach using the sorted function and the sum function:

Python3




# Python3 code to demonstrate
# sort flatten list of list
 
# initializing list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# Use the sum function to concatenate the lists in test_list and
# pass an empty list as the initial value.
# Then use the sorted function to sort the resulting list.
result = sorted(sum(test_list, []))
#Printing result
print("Original list:", test_list)
print("Flattened and sorted list:", result)
#This code is contributed by Edula Vinay Kumar Reddy


Output

Original list: [[3, 5], [7, 3, 9], [1, 12]]
Flattened and sorted list: [1, 3, 3, 5, 7, 9, 12]

This code first uses the sum function to concatenate the lists in test_list and pass an empty list as the initial value. This results in a new list that is the concatenation of the lists in test_list. Then, the sorted function is used to sort the resulting list.

In terms of time complexity, this code has a complexity of O(n * log(n)) since it needs to concatenate the lists in test_list and then sort the resulting list, which both have a complexity of O(n). In terms of space complexity, it has a complexity of O(n) since it creates a new list that is the concatenation of the lists in test_list.

Method #4 : Using sort() and extend() methods

Python3




# Python3 code to demonstrate
# sort flatten list of list
 
# 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
res=[]
for i in test_list:
    res.extend(i)
res.sort()
# print result
print("The sorted and flattened list : " + str(res))


Output

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]

Time Complexity : O(N*logN)
Auxiliary Space : O(1)

Method #5 : Using a nested for loop: 

Python3




# 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))
  
# Flattening the list of lists and storing the result in res
res = []
for sub_list in test_list:
    for item in sub_list:
        res.append(item)
# Sorting the res list
res.sort()
# Printing the sorted res list
print("The sorted and flattened list : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]

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

Method#6 : Using reduce and operator.add

Python3




import functools
import operator
 
# initialize the list of lists
test_list = [[3, 5], [7, 3, 9], [1, 12]]
# printing original list of list
print("The original list : " + str(test_list))
# use functools.reduce and operator.add to flatten the list of lists
flattened_list = functools.reduce(operator.add, test_list)
 
# sort the flattened list
sorted_list = sorted(flattened_list)
 
# print the result
print("The sorted and flattened list:", sorted_list)
#This code is contributed by Vinay Pinjala.


Output

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list: [1, 3, 3, 5, 7, 9, 12]

Time Complexity: O(N log N)
Auxiliary Space:  O(N)

Method#7: Using Recursive method.

Python3




# Python3 code to demonstrate
# sort flatten list of list
 
def flatten_and_sort(lst):
    flat_list = []
    for i in lst:
        if type(i) == list:
            flat_list.extend(flatten_and_sort(i))
        else:
            flat_list.append(i)
    return sorted(flat_list)
 
# 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 flatten_and_sort()
res = flatten_and_sort(test_list)
 
# print result
print("The sorted and flattened list : " + str(res))
#this code contributed by tvsk


Output

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]

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

Method # 8 : Using a stack

  • Create an empty stack and push the input list onto it.
  • Create an empty list to store the flattened list.
  • While the stack is not empty, pop the top element from the stack.
  • If the popped element is a list, then push its elements onto the stack.
  • If the popped element is not a list, then append it to the flattened list.
  • Sort the flattened list using the sorted() function.

Python3




def flatten_and_sort(lst):
    stack = [lst]
    flat_list = []
    while stack:
        element = stack.pop()
        if isinstance(element, list):
            stack.extend(element)
        else:
            flat_list.append(element)
    return sorted(flat_list)
 
# Example usage
test_list = [[3, 5], [7, 3, 9], [1, 12]]
print("Original list:", test_list)
result = flatten_and_sort(test_list)
print("Flattened and sorted list:", result)


Output

Original list: [[3, 5], [7, 3, 9], [1, 12]]
Flattened and sorted list: [1, 3, 3, 5, 7, 9, 12]

Time complexity: O(n log n) for the sort operation, where n is the total number of elements in the list of lists.
Auxiliary space: O(n), where n is the total number of elements in the list of lists, for the stack and flattened list.



Previous Article
Next Article

Similar Reads

Python | Flatten and Reverse Sort Matrix
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
6 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted around each tuple. Input : test_list = [[[(4, 6)]],
7 min read
Python | Ways to flatten a 2D list
Given a 2D list, Write a Python program to convert the given list into a flattened list. Method #1: Using chain.iterable() C/C++ Code # Python code to demonstrate # converting 2d list into 1d list # using chain.from_iterables # import chain from itertools import chain ini_list = [[1, 2, 3], [3, 6, 7], [7, 5, 4]] # printing initial list print (
5 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python | Flatten Tuples List to String
Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + join() The combination of above functionalities can be used
7 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split() + extend() The combination of a
7 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
Python - Flatten Dictionary with List
Given a list and dictionary, flatten dictionary with keys and values at position of available element of key in list. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {"Gfg" : 7} Output : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks'] Explanation : "Gfg" is replaced, followed by its value in dictionary. Input : test_list = ["Gfg", "
4 min read
Python Program to Flatten a Nested List using Recursion
Given a nested list, the task is to write a python program to flatten a nested list using recursion. Examples: Input: [[8, 9], [10, 11, 'geeks'], [13]] Output: [8, 9, 10, 11, 'geeks', 13] Input: [['A', 'B', 'C'], ['D', 'E', 'F']] Output: ['A', 'B', 'C', 'D', 'E', 'F'] Step-by-step Approach: Firstly, we try to initialize a variable into the linked l
3 min read
Python Program to Flatten a List without using Recursion
The task is to convert a nested list into a single list in Python i.e no matter how many levels of nesting are there in the Python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside. In other words, an element in a list c
7 min read