Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development.
Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source.
Below are some ways to achieve the above task.
Input: [[[3], [4]], [[5], [6]], [[7], [8]]] Output: [[3], [4], [5], [6], [7], [8]]
Method #1: Using simple iteration to convert a 3D list into a 2D list.
# Python code to convert a 3D list into a 2D list # Input list initialization Input = [[[3], [4]], [[5], [6]], [[7], [8]]] # Output list initialization Output = [] # Using iteration for temp in Input: for elem in temp: Output.append(elem) # printing output print("Initial 3d list is") print(Input) print("Converted 2d list is") print(Output) |
Output:
Initial 3d list is [[[3], [4]], [[5], [6]], [[7], [8]]] Converted 2d list is [[3], [4], [5], [6], [7], [8]]
Method #2: Using List Comprehension to convert a 3D list into a 2D list
# Python code to convert a 3D list into a 2D list # Input list initialization Input = [[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]] # Using list comprehension Output = [elem for twod in Input for elem in twod] # printing output print("Initial 3d list is") print(Input) print("Converted 2d list is") print(Output) |
Output:
Initial 3d list is [[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]] Converted 2d list is [[1, 1], [2, 7], [3], [4], [6, 5], [6]]
Recommended Posts:
- Python | Ways to convert list of ASCII value to string
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Ways to sum list of lists and return sum list
- Python | Convert list of numerical string to list of Integers
- Python | Convert list of string into sorted list of integer
- Python | Convert list of tuples to list of strings
- Python | Convert string enclosed list to list
- Python | Convert list of strings to list of tuples
- Python | Convert a string representation of list into list
- Python | Convert 1D list to 2D list of variable length
- Python | Convert a nested list into a flat list
- Python | Convert list of tuples into list
- Python | Convert given list into nested list
- Python | Convert list into list of lists
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



