Python | Ways to Convert a 3D list into a 2D list
Last Updated :
12 Apr, 2023
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.
Python3
# 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
Python3
# 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]]
Method #3: Using Reduce and Chain from itertools to convert a 3D list into a 2D list
Python3
# Python code to convert a 3D list into a 2D list
# importing itertools for chain
import itertools
# Input list initialization
Input = [[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]]
# Using reduce and chain
Output = list(itertools.chain.from_iterable(Input))
# printing output
print("Initial 3d list is")
print(Input)
print("Converted 2d list is")
print(Output)
#This code is contributed by Edula Vinay Kumar Reddy
OutputInitial 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]]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4:Using recursion method
APPROACH:
The approach used in this program is to recursively traverse the given input list and append the elements to the output list. Whenever we encounter a nested list, we call the flatten_list function again to flatten it and append the elements to the output list.
ALGORITHM:
1. Define a function flatten_list(lst) that takes a nested list lst as input.
2. Initialize an empty list result to store the flattened list.
3. Loop through each element in lst.
4. If the element is a list, recursively call flatten_list function and append its elements to result.
5. If the element is not a list, append it to result.
6. Return the flattened list result
Python3
def flatten_list(lst):
result = []
for elem in lst:
if isinstance(elem, list):
result.extend(flatten_list(elem))
else:
result.append(elem)
return result
input_list = [[[3], [4]], [[5], [6]], [[7], [8]]]
output_list = flatten_list(input_list)
print(output_list)
Time complexity of O(n) and space complexity of O(n), where n is the total number of elements in the 3D list.
Similar Reads
Convert Two Lists into a Dictionary - Python
We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': '
3 min read
Convert Tuple to List in Python
In Python, tuples and lists are commonly used data structures, but they have different properties:Tuples are immutable: their elements cannot be changed after creation.Lists are mutable: they support adding, removing, or changing elements.Sometimes, you may need to convert a tuple to a list for furt
2 min read
Ways to create a dictionary of Lists - Python
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key.Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
Convert a list of Tuples into Dictionary - Python
Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
3 min read
Ways to Convert a Python Dictionary to a NumPy Array
The task of converting a dictionary to a NumPy array involves transforming the dictionaryâs key-value pairs into a format suitable for NumPy. In Python, there are different ways to achieve this conversion, depending on the structure and organization of the resulting array.For example, consider a dic
3 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML appl
2 min read
How to Create a List of N-Lists in Python
In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
Convert Python List to numpy Arrays
NumPy arrays are more efficient than Python lists, especially for numerical operations on large datasets. NumPy provides two methods for converting a list into an array using numpy.array() and numpy.asarray(). In this article, we'll explore these two methods with examples for converting a list into
4 min read
Ways to Iterate Tuple List of Lists - Python
In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combi
3 min read
How to convert a Pandas Series to Python list?
In this article, we will discuss how to convert a Pandas series to a Python List and it's type. This can be done using the tolist() method.Example 1: Python3 import pandas as pd evenNumbers = [2, 4, 6, 8, 10] evenNumbersDs = pd.Series(evenNumbers) print("Pandas Series and type") print(evenNumbersDs)
2 min read