
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Grouped Flattening of list
In this tutorial, we are going to write a program that flattens a list that contains sub-lists. Given number flatten the sublists until the given number index as parts. Let's see an example to understand it clearly.
Input
lists = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] number = 2
Output
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
Let's see the steps to solve the problem.
- Initialize the list and number.
- Initialize an empty list.
- Iterate over the list with range(0, len(lists), number.
- Get the sublists using slicing lists[i:number].
- Iterate over the sublists and append the resultant list to the result list.
- Print the result.
Example
# initializing the list lists = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] number = 2 # empty list result = [] # iterating over the lists for i in range(0, len(lists), number): # appending the lists until given number index each time result.append([element for sub_list in lists[i: i + number] for element in list]) # printing the result print(result)
Output
If you run the above code, then you will get the following result.
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
Conclusion
If you have any doubts in the tutorial, mention them in the comment section.
- Related Articles
- Python Grouped summation of tuple list¶
- Grouped summation of tuple list in Python
- Flattening a Linked list in C++
- Python – Grouped Consecutive Range Indices of Elements
- Flattening arrays in JavaScript
- Flattening multi-dimensional arrays in JavaScript
- Flattening a JSON object in JavaScript
- Flattening a deeply nested array of literals in JavaScript
- Python – Sort grouped Pandas dataframe by group size?
- How to Annotate Bars in Grouped Barplot in Python?
- Array flattening using loops and recursion in JavaScript
- Python – Descending Order Sort grouped Pandas dataframe by group size?
- Python – Ascending Order Sort grouped Pandas dataframe by group size?
- Python - Convert list of string to list of list
- Convert list of string to list of list in Python

Advertisements