Write a Python program to flatten a shallow list


This program uses the itertools library to merge a list of lists (ori_list) into a single list (merged_list).

The itertools.chain() function is used to flatten the original list by taking each sub-list and combining them into a single iterable object. The * operator is used to unpack the sublists in ori_list and pass them as individual arguments to the chain() function.

The resulting merged list contains all the elements of the original sublists in the order they appear in the original lists. The final step is to convert the merged_list into a list and print it.

Source Code

import itertools
ori_list = [[20,30,70],[30,90,10], [30,20], [70,90,10,80]]
merged_list = list(itertools.chain(*ori_list))
print(merged_list)

Output

[20, 30, 70, 30, 90, 10, 30, 20, 70, 90, 10, 80]

Example Programs