How to create 2D array from list of lists in Python
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.
- list and array are not the same.
- You need to use NumPy library in order to create an array
If you have a list of lists then you can easily create 2D array from it.
Create 2D array from list in Python
Lets 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 NumPy
import 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:
- How to make a flat list out of list of lists in Python
- How to print each item from a Python list?
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:
The above type of array is also known as ranked 3 array.
To create array in NumPy we have used the below line.
codespeedy_2d_array = np.array[codespeedy_list]Learn more:
- Clockwise and CounterClockwise Rotation of Matrix using Numpy in Python
- How to use NumPy arange[] method to create arrays in Python
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Comment
Name *
Email *
Please enable JavaScript to submit this form.