Python Grouped Flattening of list

PythonServer Side ProgrammingProgramming

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.

raja
Published on 07-Jul-2020 12:34:17
Advertisements