In analyzing data or processing data using python, we come across situations where the given list has to be remodeled or reshaped to get lists with different columns. We can achieve that with multiple approaches as discussed below.
Using Slicing
We can slice the list at certain elements to create the columnar structure. Here we convert the given list into a new list where the elements are split form the middle. We sue two for loops. The outer one splits the elements from the zeroth element to the second element and the inner one from the second element to the last.
Example
x = [[5,10,15,20],[25,30,35,40],[45,50,55,60]] #Using list slicing and list comprehension print ("The Given input is : \n" + str(x)) result = [m for y in [[n[2: ], [n[0:2]]] for n in x] for m in y] print ("Converting column to separate elements in list of lists : \n" + str(result))
Output
Running the above code gives us the following result −
The Given input is : [[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]] Converting column to separate elements in list of lists : [[15, 20], [[5, 10]], [35, 40], [[25, 30]], [55, 60], [[45, 50]]]
itertools.chain() and list comprehension
Instead of two for loops we can also use the chain method from itertools. Using list comprehension we apply the same logic as above and get the result with columns split in the middle of the given list.
Example
from itertools import chain x = [[5,10,15,20],[25,30,35,40],[45,50,55,60]] #Using list slicing and list comprehension print ("The Given input is : \n" + str(x)) res = list(chain(*[list((n[2: ], [n[0:2]])) for n in x])) print ("Converting column to separate elements in list of lists : \n" + str(res))
Output
Running the above code gives us the following result −
The Given input is : [[5, 10, 15, 20], [25, 30, 35, 40], [45, 50, 55, 60]] Converting column to separate elements in list of lists : [[15, 20], [[5, 10]], [35, 40], [[25, 30]], [55, 60], [[45, 50]]]