# How to flatten a list in python

posted Oct 21

Explanation: the shortcuts based on `+` (including the implied use in `sum`) are, of necessity, `O(T**2)` when there are T sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So, for simplicity and without actual loss of generality, say you have T sublists of k items each: the first k items are copied back and forth T-1 times, the second k items T-2 times, and so on; total number of copies is k times the sum of x for x from 1 to T excluded, i.e., `k * (T**2)/2`.

The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.

Make a function which append all the elements of list of list into the flatten list.

``````def convert_flatten_list(lst_of_lst):
for i in lst_of_lst:
if(type(i)==list):
convert_flatten_list(i)
else:
flatten_lst.append(i)

lst_of_lst = [1,2,[3,4,5,[6]],[7,[8,[9]]]]
flatten_lst = []

print("Original list:",lst_of_lst)
convert_flatten_list(lst_of_lst)
print("New list:",flatten_lst) ``````

Output:

``````Original list: [1, 2, [3, 4, 5, [6]], [7, [8, [9]]]]

New list: [1, 2, 3, 4, 5, 6, 7, 8, 9]``````

1,760 points
6 1