Related Articles

Related Articles

Python | Ways to Convert a 3D list into a 2D list
  • Last Updated : 02 Aug, 2019

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :