Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Grouped Flattening of list
In this tutorial, we will write a program that performs grouped flattening of a list containing sub-lists. This technique groups consecutive sublists together and flattens them into single lists, creating chunks of a specified size.
Problem Statement
Given a list of sublists and a number, we need to group the sublists in chunks of the given number and flatten each group into a single list.
Input
lists = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] number = 2
Expected Output
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
Step-by-Step Approach
Let's break down the solution process ?
- Initialize the list of sublists and the grouping number
- Create an empty result list to store flattened groups
- Iterate through the list with step size equal to the number
- For each iteration, slice the sublists and flatten them
- Append the flattened group to the result list
Implementation
# initializing the list of sublists
lists = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
number = 2
# empty result list
result = []
# iterating over the lists with step size equal to number
for i in range(0, len(lists), number):
# grouping and flattening sublists
flattened_group = [element for sub_list in lists[i: i + number] for element in sub_list]
result.append(flattened_group)
# printing the result
print(result)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
How It Works
The algorithm uses range(0, len(lists), number) to iterate through indices with a step size equal to the grouping number. For each iteration, it takes a slice lists[i: i + number] and flattens it using a nested list comprehension.
Another Example
Let's try with a different grouping size ?
# different example with group size 3
lists = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
number = 3
result = []
for i in range(0, len(lists), number):
flattened_group = [element for sub_list in lists[i: i + number] for element in sub_list]
result.append(flattened_group)
print(result)
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
Conclusion
Grouped flattening is useful when you need to reorganize nested data into larger chunks. The key is using the step parameter in range() to group consecutive sublists and then flattening each group using list comprehension.
