Open In App

Python | Grouped Flattening of list

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

The problem of flattening a list is quite common, but sometimes, we need to perform the flattening but in the grouped manner, i.e getting the sublists of size K and flatten them. This particular utility has use-cases in many domains including web-development and day-day programming as well. Let’s discuss certain ways in which this can be done. 

Method #1 : Using list comprehension + list slicing This problem can be approached by using the list comprehension and also applying list slicing to limit the grouping and binding the list is done as a part of list comprehension logic. 

Python3




# Python3 code to demonstrate
# group flattening of list
# using list comprehension + list slicing
 
# initializing list of lists
test_list = [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
 
# printing original list
print("The original list : " +  str(test_list))
 
# declaring K
K = 3
 
# using list comprehension + list slicing
# group flattening of list
res = [[i for sub in test_list[j : j + K] for i in sub]
                  for j in range(0, len(test_list), K)]
 
# printing result
print("The grouped flattened list :  " + str(res))


Output : 

The original list : [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
The grouped flattened list :  [[1, 3, 3, 4, 6, 5], [4, 5, 7, 6, 7, 9]]

Time Complexity: O(N * K), where N is the number of sublists in test_list and K is the size of the sublist.

Space Complexity: O(N * K)..

Method #2 : Using list comprehension + zip() + map() This problem can also be solved using the combination of the above 3 functions. The zip function is used to get all the groups into one and map function is used to convert the iterator into list and list comprehension performs the task of grouping. 

Python3




# Python3 code to demonstrate
# group flattening of list
# using list comprehension + zip() + map()
 
# initializing list of lists
test_list = [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
 
# printing original list
print("The original list : " +  str(test_list))
 
# declaring K
K = 3
 
# using list comprehension + zip() + map()
# group flattening of list
res = list(map(list, zip(*[iter([i for sub in test_list
              for i in sub])]*(K * len(test_list[0])))))
 
# printing result
print("The grouped flattened list :  " + str(res))


Output : 

The original list : [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
The grouped flattened list :  [[1, 3, 3, 4, 6, 5], [4, 5, 7, 6, 7, 9]]

Method #3: Using itertools.zip_longest()

Iterate over the sublists in the input list in groups of size K and Flatten the group and append it to the result list

Python3




import itertools
 
# Python3 code to demonstrate
# group flattening of list
# using list comprehension + list slicing
 
# initializing list of lists
l = [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
 
# printing original list
print("The original list : " + str(l))
 
# declaring K
K = 3
# Initialize an empty result list
result = []
 
# Iterate over the sublists in the input list in groups of size K
for group in itertools.zip_longest(*[iter(l)] * K):
    # Flatten the group and append it to the result list
    result.append([item for sublist in group for item in sublist])
 
# Return the result list
print(result)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
[[1, 3, 3, 4, 6, 5], [4, 5, 7, 6, 7, 9]]

The time complexity of the above code is O(n), where n is the number of elements in the input list. This is because the code iterates over the input list once to create the groups and then iterates over each group to flatten it.

The space complexity is also O(n), as the result list has the same number of elements as the input list. The itertools.zip_longest() function creates an iterator that returns tuples containing the elements of the input list in groups of size K, but this iterator is not stored in memory, so it does not contribute to the space complexity.

Method #4: Using nested loops

Step-by-step approach:

  • Initialize the list of lists named test_list.
  • Print the original list using the print() function.
  • Declare a variable K with value 3.
  • Initialize an empty list res.
  • Use a for loop to iterate through the elements of the list test_list. The loop starts at 0, ends at the length of test_list, and increments by K.
  • Create an empty list named temp inside the outer loop.
  • Use another for loop to iterate through the sublists of test_list. The loop iterates from j to j+K, where j is the current value of the outer loop.
  • Use another for loop inside the previous for loop to iterate through the elements of each sublist.
  • Append each element to the list temp.
  • Append temp to the list res.
  • Print the result using the print() function.

Python3




# Python3 code to demonstrate
# group flattening of list
# using for loop and append()
 
# initializing list of lists
test_list = [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# declaring K
K = 3
 
# using for loop and append()
# group flattening of list
res = []
for j in range(0, len(test_list), K):
    temp = []
    for sub in test_list[j:j+K]:
        for i in sub:
            temp.append(i)
    res.append(temp)
 
# printing result
print("The grouped flattened list :  " + str(res))


Output

The original list : [[1, 3], [3, 4], [6, 5], [4, 5], [7, 6], [7, 9]]
The grouped flattened list :  [[1, 3, 3, 4, 6, 5], [4, 5, 7, 6, 7, 9]]

Time complexity: O(N^2), where N is the length of the input list.
Auxiliary space: O(NK), where N is the length of the input list and K is the group size. 



Previous Article
Next Article

Similar Reads

Python - Value List Key Flattening
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform pairing of each value of keys to extract the flattened dictionary. This kind of problem can have application in data domains. Lets discuss certain way in which this task can be performed. Method #1: Using loop This is brute way in which this task ca
7 min read
Python Program For Flattening A Multilevel Linked List
Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the below figure. You are given the head of the first level of the list. Flatten the lis
4 min read
Python Program For Flattening A Linked List
Given a linked list where every node represents a linked list and contains two pointers of its type: Pointer to next node in the main list (we call it 'right' pointer in the code below).Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below). All linked lists are sorted. See the following example 5 ->
4 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard module
3 min read
Python | Grouped summation of tuple list
Many times, we are given a list of tuples and we need to group its keys and perform certain operations while grouping. The most common operation is addition. Let's discuss certain ways in which this task can be performed. Apart from addition, other operations can also be performed by doing small changes. Method 1: Using Counter() + "+" operator Thi
10 min read
Python - Multiple Keys Grouped Summation
Sometimes, while working with Python records, we can have a problem in which, we need to perform elements grouping based on multiple key equality, and also summation of the grouped result of a particular key. This kind of problem can occur in applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_
10 min read
Python - Grouped Consecutive Range Indices of Elements
Given List of elements, for list of tuples, where each represents the continuity of occurrence of each element. Input : test_list = [1, 1, 5, 6, 5, 5] Output : {1: [(0, 1)], 5: [(2, 2), (4, 5)], 6: [(3, 3)]} Explanation : 5 present at 2nd idx and also in continuation in 4th and 5th index, and hence recorded range. Input : test_list = [5, 5, 5, 5, 5
8 min read
How to Make Grouped Violinplot with Seaborn in Python?
This article depicts how to make a grouped violinplot with Seaborn in python. Violinplot is a great way of visualizing the data as a combination of the box plot with the kernel density plots to produce a new type of plot. For this article, we will be using the iris dataset to plot data. This comes inbuilt in seaborn and can be loaded with the load_
3 min read
How to Annotate Bars in Grouped Barplot in Python?
A Barplot is a graph that represents the relationship between a categoric and a numeric feature. Many rectangular bars correspond to each category of the categoric feature and the size of these bars represents the corresponding value. Using grouped bar plots, we can study the relationship between more than two features. In Python, we can plot a bar
3 min read
Grouped Boxplots in Python with Seaborn
Boxplot depicts the distribution of quantitative data facilitating comparisons between different variables, continuous or categorical. It is a common data dispersion measure. Boxplots consist of a five-number summary which helps in detecting and removing outliers from the dataset. Minimum observationQ1 (25% or Quartile 1)Median or Q2Q3 (75% or Quar
2 min read
Practice Tags :