Open In App

Python – Convert 2D list to 3D at K slicing

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Convert 2D list to 3D at K slicing
# Using loop
 
# initializing list
test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Convert 2D list to 3D at K slicing
# Using loop
res = []
subl = []
cnt = 0
for sub in test_list:
    subl.append(sub)
    cnt = cnt + 1
    if cnt >= K:
        res.append(subl)
        subl = []
        cnt = 0
 
# printing result
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




# Python3 code to demonstrate working of
# Convert 2D list to 3D at K slicing
# Using zip() + list comprehension
 
# initializing list
test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# Convert 2D list to 3D at K slicing
# Using zip() + list comprehension
test_list = iter(test_list)
temp = [test_list] * K
res = [list(ele) for ele in zip(*temp)]
 
# printing result
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
 
# initializing list
test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
 
# initializing K
K = 2
 
# Convert 2D list to 3D at K slicing
# Using itertools.islice()
it = iter(test_list)
res = [list(itertools.islice(it, K)) for _ in range(len(test_list)//K)]
 
# printing result
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

Python | Slicing list from Kth element to last element
Python list slicing slices the list from start index till end - 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let's discuss ways in which last element can be included during a list slice. Method #1 : Using None During list slicing, giving the d
6 min read
Python | Variable list slicing
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths 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. Method #1 : Using itertools.islice() + list comprehension The list com
7 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 comprehension can be used to perform this particular ta
6 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax of list slicin
4 min read
Python | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 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. Method #1 : Using itertools.islice() + sum() + list
7 min read
Python List Slicing
In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems. Consider a Python list, in order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:). With this operator, one can specify where to start the
5 min read
Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Slicing List of Tuples in Python
Slicing, a powerful feature in Python, allows us to extract specific portions of data from sequences like lists. When it comes to lists of tuples, slicing becomes a handy tool for extracting and manipulating data. In this article, we'll explore five simple and versatile methods to slice lists of tuples in Python, accompanied by code examples. Slici
2 min read