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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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]]


My Personal Notes arrow_drop_up


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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.