Python – Convert 2D list to 3D at K slicing
Last Updated :
13 Mar, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] , K = 3
Output : [[[6, 5], [2, 3], [3, 1]], [[4, 6], [3, 2], [1, 6]]]
Input : test_list = [[6, 5], [2, 3], [3, 1]] , K = 1
Output : [[[6, 5]], [[2, 3]], [[3, 1]]]
Method #1: Using loop This is brute way in which this task can be performed. In this, we iterate through each element, and maintain a counter, at every Kth sublist, create a new list and append accordingly.
Python3
test_list = [[ 6 , 5 ], [ 2 , 3 ], [ 3 , 1 ], [ 4 , 6 ], [ 3 , 2 ], [ 1 , 6 ]]
print ("The original list is : " + str (test_list))
K = 2
res = []
subl = []
cnt = 0
for sub in test_list:
subl.append(sub)
cnt = cnt + 1
if cnt > = K:
res.append(subl)
subl = []
cnt = 0
print ("Records after conversion : " + str (res))
|
Output :
The original list is : [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
Records after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]
Time complexity: O(n), where n is the length of the input list. The program uses a loop to iterate through the input list once.
Auxiliary Space: O(k), where k is the value of K. The program creates a new list of sublists for each group of K elements in the input list. The size of each sublist is at most K, so the total auxiliary space used by the program is O(k).
Method #2 : Using zip() + list comprehension The combination of above functions can also be used to solve this problem. In this, we perform task by first chunking the values according to size and then list comprehension along with zip() is used for dimension conversion.
Python3
test_list = [[ 6 , 5 ], [ 2 , 3 ], [ 3 , 1 ], [ 4 , 6 ], [ 3 , 2 ], [ 1 , 6 ]]
print ("The original list is : " + str (test_list))
K = 2
test_list = iter (test_list)
temp = [test_list] * K
res = [ list (ele) for ele in zip ( * temp)]
print ("Records after conversion : " + str (res))
|
Output :
The original list is : [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
Records after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]
Time complexity: O(n), where n is the number of elements in the 2D list.
Auxiliary space: O(n/K), where K is the slicing index. The program creates a temporary list of length K,
Method #3: Using itertools.islice()
The itertools module provides the islice() function, which can be used to slice an iterable object like a list or a tuple. We can use islice() to split the 2D list into chunks of size K and then convert each chunk to a sublist of a new 3D list.
Python3
import itertools
test_list = [[ 6 , 5 ], [ 2 , 3 ], [ 3 , 1 ], [ 4 , 6 ], [ 3 , 2 ], [ 1 , 6 ]]
K = 2
it = iter (test_list)
res = [ list (itertools.islice(it, K)) for _ in range ( len (test_list) / / K)]
print ( "Records after conversion : " + str (res))
|
Output
Records after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]
Time complexity: O(N/K * K), which simplifies to O(N), where N is the number of elements in the 2D list.
Auxiliary space: O(K), which is the size of each sublist that we create using islice().
Similar Reads
Slice a 2D List in Python
Slicing a 2D list in Python is a common task when working with matrices, tables, or any other structured data. It allows you to extract specific portions of the list, making it easier to manipulate and analyze the data. In this article, we'll explore four simple and commonly used methods to slice a
4 min read
Python | Alternate range slicing in list
List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let's discuss how this particular problem can be solved. Method #1 : Using list comprehension List compr
6 min read
Python | Custom List slicing Sum
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Letâs discuss certain ways in which this can be done. Me
7 min read
Convert a Dictionary to a List in Python
In Python, dictionaries and lists are important data structures. Dictionaries hold pairs of keys and values, while lists are groups of elements arranged in a specific order. Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dict
3 min read
Slice till K Dictionary Value Lists - Python
The task of slicing the values in a dictionary involves extracting a portion of the list associated with each key, up to a specified index k. This can be achieved by iterating over the dictionary, slicing each list up to the k-th index and storing the result in a new dictionary. For example, given a
4 min read
How To Reverse A List In Python Using Slicing
In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems. In this article, we will see how we can reverse a list using slicing in Python. Reverse a List Using Slicing in PythonBelow are some of the examples by which we can perform rev
3 min read
Python - Slicing List from Kth Element to Last Element
We are given a list we need to slice list from Kth element to last element. For example, n = [10, 20, 30, 40, 50] we nee do slice this list from K=2 element so that resultant output should be [30, 40, 50]. Using List SlicingList slicing allows extracting a portion of a list using the syntax list[k:]
3 min read
How to Split Lists in Python?
Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
3 min read
Slice a 2D Array in Python
We are given a 2D array matrix and we have to Slice this matrix 2D array and return the result. In this article, we will see how we can Slice the 2D array in Python. Example Input : matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output : [[ 4, 5, 6]] Explanation : We can see that 2D array (matrix) is
3 min read
Convert List to Single Dictionary Key - Value list - Python
We are given a list and a element K, our aim is to transform the given list into a dictionary where the specified element (Kth element) becomes the key and the rest of the elements form the value list. For example: if the given list is: [6, 5, 3, 2] and K = 1 then the output will be {5: [6, 3, 2]}.
4 min read