A list is a data structure that allows you to store multiple values of objects in a single variable. Suppose you have a list and want to convert it into a 2D Array in python then how you will do it? In this entire tutorial, you will learn how to convert a list to a 2D array with various methods.
Before going to the demonstration part first create a sample list that will be used to implement the various method.
Run the below lines of code to create a dummy list.
my_list = [10,20,30,40,50,60,70,80]
Let’s know all the methods to convert the list to a 2D array.
In this method, I will use the numpy python package for the conversion of the list to a 2D array. Use the below lines of code to implement the conversion.
import numpy as np
my_list = [10,20,30,40,50,60,70,80]
final_list=[]
numpy_array = np.array(my_list).reshape(-1, 2)
list_2d = list(numpy_array)
for e in range(len(list_2d)):
final_list.append(list(list_2d[e]))
print(final_list)
Here I have created an empty list that will store all the elements of the list converted in a numpy array as a list. You will get the output as below.
Output
The second method to convert a list to 2d without numpy is the use of the custom function. Here you will define some algo that will convert any list to a 2d array of any dimensions. Let’s create the function using the below lines of code.
def list_2d(list1,rows, columns):
result=[]
start = 0
end = columns
for i in range(rows):
result.append(list1[start:end])
start +=columns
end += columns
return result
Let’s say the list is to be converted to 2 rows and 4 columns then I will add the below lines of code.
my_list = [10,20,30,40,50,60,70,80]
list_2d(my_list,2, 4)
Output
In the same way, you can use 3 and 4 for 3 rows and 4 columns.
There can be many ways or methods to convert the list to a 2D array. Here I have written the best two methods to convert any list to a 2D array. One with NumPy and one without numpy or simply custom function.
I hope you have liked this article. If you have any query and wants to add some suggestion then you can contact us for more help.