Convert list of array to 2D array Python
How to create 2D array from list of lists in Python By Saruque Ahamed Mollick This Python tutorial will show you how to create a 2D array from a list of lists in Python. To learn this you need to have the below basic concepts of Python. Show
If you have a list of lists then you can easily create 2D array from it. Create 2D array from list in PythonLets understand this with an example. Here is our list. codespeedy_list = [[4,6,2,8],[7,9,6,1],[12,74,5,36]]Now we need to create a 2D array from this list of lists. (Also known as a ranked two array) Python Program to create 2D array in NumPyimport numpy as np codespeedy_list = [[4,6,2,8],[7,9,6,1],[12,74,5,36]] codespeedy_2d_array = np.array(codespeedy_list) print(codespeedy_2d_array)Output: $ python codespeedy.py [[ 4 6 2 8] [ 7 9 6 1] [12 74 5 36]]If you wish you can also read:
Explanation of the program: At first, we have imported NumPy library by the below line of code: import numpy as npYou can write anything instead of np. But writing np is globally accepted term. Thus it will be a good practice for us to write np instead of something else. Then you can see we have taken a list, codespeedy_list We also provided some elements in it. This type of lists is also known as a list of lists. Because in our list we have 3 lists. We have used a list of lists because our main goal is to create a 2d array. If you want to create a 3d array then you can put another list in every list of our list. Just like below: [[[45,12],[85,15]],[[254,14],[451,13]]] The above type of array is also known as ranked 3 array. To create array in NumPy we have used the below line. Learn more:
Leave a Reply Cancel replyYour email address will not be published. Required fields are marked * Comment Name * Email * Please enable JavaScript to submit this form. |