flatten lists in python
Introduction to flatten lists in python
This concept of flatten lists in python is quite useful as well as popular among programmers. An example of the same is shown below. Suppose one has a list as shown here:
To convert this list into the format shown below one needs to use the concept of flattened lists in python. The result is as follows:
The code for the same is:
flat_list = [] for sublist in l: for item in sublist: flat_list.append(item)
The output for the above code is the same as shown before in the post. One can also use the timeit module to achieve the same.
Explanation: When there are L sublists, the shortcuts based on + (including the implied use in sum) must be O(L**2) because as the intermediate result list gets longer, a new intermediate result list object must be allocated at each step, and all the items in the prior intermediate result must be copied over (as well as a few new ones added at the end).
Say you have L sublists, each with I items. The first I items are copied L-1 times, the second I items L-2 times, and so on. The total number of copies is therefore I times the sum of x, with x from 1 to L omitted, or I * (L**2)/2.
Also Read: rmarkdown figure auto-adjust HTML