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

Let’s 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:



Explanation of the program:

At first, we have imported NumPy library by the below line of code:

import numpy as np

You 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.

codespeedy_2d_array = np.array(codespeedy_list)

Learn more:

Leave a Reply

Your email address will not be published. Required fields are marked *