Python | Convert column to separate elements in list of lists
Last Updated :
02 May, 2023
There are instances in which we might require to extract a particular column of a Matrix and assign its each value as separate entity in list and this generally has a utility in Machine Learning domain. Let's discuss certain ways in which this action can be performed.
Method #1 : Using list slicing and list comprehension
The functionality of list slicing and comprehension can be clubbed to perform the particular task of extracting a column from a list and then it can be added as new element using list comprehension.
Python3
# Python3 code to demonstrate
# column to separate elements in list of lists
# using list slicing and list comprehension
# initializing list of list
test_list = [[1, 3, 4],
[6, 2, 8],
[9, 10, 5]]
# printing original list
print ("The original list is : " + str(test_list))
# using list slicing and list comprehension
# column to separate elements in list of lists
res = [i for nest_list in [[j[1 : ], [j[0]]]
for j in test_list] for i in nest_list]
# printing result
print ("The list after column shift is : " + str(res))
OutputThe original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]
The time complexity of this program is O(n^2) where n is the number of elements in the list of lists.
The auxiliary space complexity of this program is O(n), where n is the number of elements in the list of lists
Method #2 : Using itertools.chain() + list comprehension + list slicing
The above method can be improved by inducing the concept of element chaining and reduce the overhead of the list comprehension and reducing the time taken to execute this particular task.
Python3
# Python3 code to demonstrate
# column to separate elements in list of lists
# using itertools.chain()+ list comprehension + list slicing
from itertools import chain
# initializing list of list
test_list = [[1, 3, 4],
[6, 2, 8],
[9, 10, 5]]
# printing original list
print ("The original list is : " + str(test_list))
# using itertools.chain() + list comprehension + list slicing
# column to separate elements in list of lists
res = list(chain(*[list((sub[1: ], [sub[0]]))
for sub in test_list]))
# printing result
print ("The list after column shift is : " + str(res))
OutputThe original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Approach using numpy:
Note: Install numpy module using command "pip install numpy"
Algorithm:
Initialize the input list of lists, test_list.
Convert the test_list into a NumPy array, arr.
Perform column shift using np.roll() function and save the result in shifted_arr.
Convert the shifted_arr array back to a list of lists, shifted_list.
Initialize an empty list res.
Loop through each sublist of shifted_list and divide them into two sublists, each containing two elements using list slicing.
Append the two sublists to res.
Print the original list and the modified list res.
Python3
import numpy as np
# initializing list of list
test_list = [[1, 3, 4],
[6, 2, 8],
[9, 10, 5]]
# convert the list to a NumPy array
arr = np.array(test_list)
# shift the columns
shifted_arr = np.roll(arr, -1, axis=1)
# convert the shifted array back to a list of lists
shifted_list = shifted_arr.tolist()
res=[]
for i in shifted_list:
res.extend([i[:2], i[2:]])
# print the original list and the shifted list
print("The original list is :", test_list)
print("The list after column shift is :", res)
Output:
The original list is : [[1, 3, 4], [6, 2, 8], [9, 10, 5]]
The list after column shift is : [[3, 4], [1], [2, 8], [6], [10, 5], [9]]
Time complexity:
The time complexity of the code is O(n^2), where n is the number of elements in the input list of lists. This is due to the loop that is used to split the sublists into smaller sublists.
Auxiliary Space:
The space complexity of the code is also O(n^2), as the input list of lists is converted to a NumPy array and then converted back to a list of lists, which requires additional memory. Additionally, a new list res is created to store the divided sublists.
Similar Reads
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read
Convert Value List Elements to List Records - Python
We are given a dictionary with lists as values and the task is to transform each element in these lists into individual dictionary records. Specifically, each list element should become a key in a new dictionary with an empty list as its value. For example, given {'gfg': [4, 5], 'best': [8, 10, 7, 9
3 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
3 min read
Python - Column-wise elements in Dictionary value list
Given dictionary with value list, extract elements columnwise. Input : test_dict = {'Gfg' : [3, 6], 'is' : [4, 2], 'best' :[9, 1]} Output : [3, 4, 9, 6, 2, 1] Explanation : 3, 4, 9 from col1 and then 6, 2, 1 from 2 are extracted in order. Input : test_dict = {'Gfg' : [3], 'is' : [4], 'best' :[9]} Ou
3 min read
Python | Convert List of lists to list of Strings
Interconversion of data is very popular nowadays and has many applications. In this scenario, we can have a problem in which we need to convert a list of lists, i.e matrix into list of strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + joi
4 min read
Convert List of Lists to Dictionary - Python
We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isd
6 min read
Python | Convert list into list of lists
Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists. Examples: Input : ['alice', 'bob', 'cara'] Output : [['alice'], ['bob'], ['cara']] Input : [101, 202, 303, 404, 505] Output : [[101], [202],
5 min read
Convert 1D list to 2D list of variable length- Python
The task of converting a 1D list to a 2D list of variable length in Python involves dynamically dividing a single list into multiple sublists, where each sublist has a different number of elements based on a specified set of lengths.For example, given a list [1, 2, 3, 4, 5, 6] and length specificati
4 min read
Python | Column deletion from list of lists
The problem of removing a row from a list is quite simple and we just need to pop a list out of lists . But there can be a utility where we need to delete a column i.e particular index element of each of the list. This is problem that can occur if we store any database data into containers. Let's di
4 min read