# Python | Grouped Flattening of list

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.

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