List to 2D matrix Python

Short answer: Convert a list of lists—let’s call it l—to a NumPy array by using the standard np.array[l] function. This works even if the inner lists have a different number of elements.

Convert List of Lists to 2D Array

Problem: Given a list of lists in Python. How to convert it to a 2D NumPy array?

Example: Convert the following list of lists

[[1, 2, 3], [4, 5, 6]]

into a NumPy array

[[1 2 3] [4 5 6]]

Solution: Use the np.array[list] function to convert a list of lists into a two-dimensional NumPy array. Here’s the code:

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5, 6]] # Convert it to a NumPy array a = np.array[lst] # Print the resulting array print[a] ''' [[1 2 3] [4 5 6]] '''

Try It Yourself: Here’s the same code in our interactive code interpreter:

Hint: The NumPy method np.array[] takes an iterable as input and converts it into a NumPy array.

Convert a List of Lists With Different Number of Elements

Problem: Given a list of lists. The inner lists have a varying number of elements. How to convert them to a NumPy array?

Example: Say, you’ve got the following list of lists:

[[1, 2, 3], [4, 5], [6, 7, 8]]

What are the different approaches to convert this list of lists into a NumPy array?

Solution: There are three different strategies you can use. [source]

[1] Use the standard np.array[] function.

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array a = np.array[lst] # Print the resulting array print[a] ''' [list[[1, 2, 3]] list[[4, 5]] list[[6, 7, 8]]] '''

This creates a NumPy array with three elements—each element is a list type. You can check the type of the output by using the built-in type[] function:

>>> type[a]

[2] Make an array of arrays.

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5], [6, 7, 8]] # Convert it to a NumPy array a = np.array[[np.array[x] for x in lst]] # Print the resulting array print[a] ''' [array[[1, 2, 3]] array[[4, 5]] array[[6, 7, 8]]] '''

This is more logical than the previous version because it creates a NumPy array of 1D NumPy arrays [rather than 1D Python lists].

[3] Make the lists equal in length.

# Import the NumPy library import numpy as np # Create the list of lists lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]] # Calculate length of maximal list n = len[max[lst, key=len]] # Make the lists equal in length lst_2 = [x + [None]*[n-len[x]] for x in lst] print[lst_2] # [[1, 2, 3, None], [4, 5, None, None], [6, 7, 8, 9]] # Convert it to a NumPy array a = np.array[lst_2] # Print the resulting array print[a] ''' [[1 2 3 None] [4 5 None None] [6 7 8 9]] '''

You use list comprehension to “pad” None values to each inner list with smaller than maximal length.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

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.

  • 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:


In real-world Often tasks have to store rectangular data table. [say more on this!] Such tables are called matrices or two-dimensional arrays. In Python any table can be represented as a list of lists [a list, where each element is in turn a list]. For example, here's the program that creates a numerical table with two rows and three columns, and then makes some manipulations with it:

None a = [[1, 2, 3], [4, 5, 6]] print[a[0]] print[a[1]] b = a[0] print[b] print[a[0][2]] a[0][1] = 7 print[a] print[b] b[2] = 9 print[a[0]] print[b]

The first element of a here — a[0] — is a list of numbers [1, 2, 3]. The first element of this new list is a[0][0] == 1; moreover, a[0][1] == 2, a[0][2] == 3, a[1][0] == 4, a[1][1] == 5, a[1][2] == 6.

To process 2-dimensional array, you typically use nested loops. The first loop iterates through the row number, the second loop runs through the elements inside of a row. For example, that's how you display two-dimensional numerical list on the screen line by line, separating the numbers with spaces:

None a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] for i in range[len[a]]: for j in range[len[a[i]]]: print[a[i][j], end=' '] print[]

We have already tried to explain that a for-loop variable in Python can iterate not only over a range[], but generally over all the elements of any sequence. Sequences in Python are lists and strings [and some other objects that we haven't met yet]. Look how you can print a two-dimensional array, using this handy feature of loop for:

None a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] for row in a: for elem in row: print[elem, end=' '] print[]

Naturally, to output a single line you can use method join[]:

for row in a: print[' '.join[[str[elem] for elem in row]]]

This is how you can use 2 nested loops to calculate the sum of all the numbers in the 2-dimensional list:

None a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] s = 0 for i in range[len[a]]: for j in range[len[a[i]]]: s += a[i][j] print[s]

Or the same with iterating by elements, not by the variables i and j:

None a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] s = 0 for row in a: for elem in row: s += elem print[s]

Advertising by Google, may be based on your interests

Suppose that two numbers are given: the number of rows of n and the number of columns m. You must create a list of size n×m, filled with, say, zeros.

The obvious solution appears to be wrong:

a = [[0] * m] * n

This can be easily seen if you set the value of a[0][0] to 5, and then print the value of a[1][0] — it will also be equal to 5. The reason is, [0] * m returns just a reference to a list of m zeros, but not a list. The subsequent repeating of this element creates a list of n items that all reference to the same list [just as well as the operation b = a for lists does not create the new list], so all rows in the resulting list are actually the same string.

Using our visualizer, keep track of the id of lists. If two lists have the same id number, it's actually the same list in memory.

None n = 3 m = 4 a = [[0] * m] * n a[0][0] = 5 print[a[1][0]]

Thus, a two-dimensional list cannot be created simply by repeating a string. What to do?..

A possible way: you can create a list of n elements [say, of n zeros] and then make each of the elements a link to another one-dimensional list of m elements:

None n = 3 m = 4 a = [0] * n for i in range[n]: a[i] = [0] * m

Another [but similar] way: create an empty list and then append a new element to it n times [this element should be a list of length m]:

None n = 3 m = 4 a = [] for i in range[n]: a.append[[0] * m]

But the easiest way is to use generator, creating a list of n elements, each of which is a list of m zeros:

None n = 3 m = 4 a = [[0] * m for i in range[n]]

In this case each element is created independently from the others. The list [0] * m is n times consructed as the new one, and no copying of references occurs.

Advertising by Google, may be based on your interests

Say, a program takes on input two-dimensional array in the form of n rows, each of which contains m numbers separated by spaces. How do you force the program to read it? An example of how you can do it:

3 1 2 3 4 5 6 7 8 9 # the first line of input is the number of rows of the array n = int[input[]] a = [] for i in range[n]: a.append[[int[j] for j in input[].split[]]]

Or, without using sophisticated nested calls:

3 1 2 3 4 5 6 7 8 9 # the first line of input is the number of rows of the array n = int[input[]] a = [] for i in range[n]: row = input[].split[] for i in range[len[row]]: row[i] = int[row[i]] a.append[row]

You can do the same with generators:

3 1 2 3 4 5 6 7 8 9 # the first line of input is the number of rows of the array n = int[input[]] a = [[int[j] for j in input[].split[]] for i in range[n]]

Advertising by Google, may be based on your interests

Suppose you are given a square array [an array of n rows and n columns]. And suppose you have to set elements of the main diagonal equal to 1 [that is, those elements a[i][j] for which i==j], to set elements above than that diagonal equal to 0, and to set elements below that diagonal equal to 2. That is, you need to produce such an array [example for n==4]:

1 0 0 0 2 1 0 0 2 2 1 0 2 2 2 1 [In this case you can do it manually by setting a[0][0] = 1, a[0][1] = 0 and so on, but you won't do it manually for arrays of 100 rows and 100 columns, which are often the case.]

We are eager to show you several ways of solving this problem. First, note that elements that lie above the main diagonal – are elements a[i][j] for which ij. Thus, we can compare the values i and j, which determines the value of a[i][j]. We get the following algorithm:

None n = 4 a = [[0] * n for i in range[n]] for i in range[n]: for j in range[n]: if i < j: a[i][j] = 0 elif i > j: a[i][j] = 2 else: a[i][j] = 1 for row in a: print[' '.join[[str[elem] for elem in row]]]

This algorithm is slow: it uses two loops and for each pair [i,j] executes one or two if instructions. If we complicate the algorithm, we will be able to do it without a conditional statement.

First, fill the main diagonal, for which we will need one loop:

for i in range[n]: a[i][i] = 1

Then fill with zeros all the elements above the main diagonal. To make this, for each row with the number i you need to assign a value to a[i][j] for j=i+1, ..., n-1. To do that, you need nested loops:

for i in range[n]: for j in range[i + 1, n]: a[i][j] = 0

By analogy, for j=0, ..., i-1 set the elements a[i][j] equal to 2:

for i in range[n]: for j in range[0, i]: a[i][j] = 2

You can combine all this code and receive another solution:

None n = 4 a = [[0] * n for i in range[n]] for i in range[n]: for j in range[0, i]: a[i][j] = 2 a[i][i] = 1 for j in range[i + 1, n]: a[i][j] = 0 for row in a: print[' '.join[[str[elem] for elem in row]]]

Here's another solution, which repeats lists to build the next rows of the list. The i-th line of the list consists of i numbers 2, followed by one integer 1, followed by n-i-1 zeros:

None n = 4 a = [0] * n for i in range[n]: a[i] = [2] * i + [1] + [0] * [n - i - 1] for row in a: print[' '.join[[str[elem] for elem in row]]]

As usual, you can replace the loop with the generator:

None n = 4 a = [0] * n a = [[2] * i + [1] + [0] * [n - i - 1] for i in range[n]] for row in a: print[' '.join[[str[elem] for elem in row]]]

Advertising by Google, may be based on your interests

You can use nested generators to create two-dimensional arrays, placing the generator of the list which is a string, inside the generator of all the strings. Recall that you can create a list of n rows and m columns using the generator [which creates a list of n elements, where each element is a list of m zeros]:

[[0] * m for i in range[n]]

But the internal list can also be created using, for example, such generator: [0 for j in range[m]]. Nesting one generator into another, we obtain

[[0 for j in range[m]] for i in range[n]]

How is it related to our problem? The thing is, if the number 0 is replaced by some expression that depends on i [the line number] and j [the column number], you get the matrix filled according to some formula.

For example, suppose you need to initialize the following array [for convenience, extra spaces are added between items]:

0 0 0 0 0 0 0 1 2 3 4 5 0 2 4 6 8 10 0 3 6 9 12 15 0 4 8 12 16 20

In this array there are n = 5 rows, m = 6 columns, and the element with row index i and column index j is calculated by the formula a[i][j] = i * j.

As always, you could use generator to create such an array:

[[i * j for j in range[m]] for i in range[n]]

Advertising by Google, may be based on your interests

Video liên quan

Chủ Đề