Array of list to array python

Introduction

With NumPy, [np.array] objects can be converted to a list with the tolist[] function. The tolist[] function doesn’t accept any arguments. If the array is one-dimensional, a list with the array elements is returned. For a multi-dimensional array, a nested list is returned.

Converting one-dimensional NumPy Array to List

Let’s construct a one-dimensional array of [1, 2, 3]:

import numpy as np

# 1d array to list
arr_1 = np.array[[1, 2, 3]]

print[f'NumPy Array:\n{arr_1}']

This code will output:

NumPy Array:
[1 2 3]

Now, let’s use tolist[]:

import numpy as np

# 1d array to list
arr_1 = np.array[[1, 2, 3]]

print[f'NumPy Array:\n{arr_1}']

list_1 = arr_1.tolist[]

print[f'List: {list_1}']

This new code will output:

List: [1, 2, 3]

The array has been converted from numpy scalars to Python scalars.

Converting multi-dimensional NumPy Array to List

Let’s construct a multi-dimensional array of [ [1, 2, 3], [4, 5, 6] ]:

import numpy as np

# 2d array to list
arr_2 = np.array[[[1, 2, 3], [4, 5, 6]]]

print[f'NumPy Array:\n{arr_2}']

This code will output:

NumPy Array:
[[1 2 3]
 [4 5 6]]

Now, let’s use tolist[]:

import numpy as np

# 2d array to list
arr_2 = np.array[[[1, 2, 3], [4, 5, 6]]]

print[f'NumPy Array:\n{arr_2}']

list_2 = arr_2.tolist[]

print[f'List: {list_2}']

This new code will output:

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

The array has been converted from numpy scalars to Python scalars.

Conclusion

In this article, you learned how to use tolist[] to convert np.array objects to lists. It is applicable to one-dimensional and multi-dimensional arrays.

References

  • API Documentation

I'm trying to turn a list of 2d numpy arrays into a 2d numpy array. For example,

dat_list = []
for i in range[10]:
    dat_list.append[np.zeros[[5, 10]]]

What I would like to get out of this list is an array that is [50, 10]. However, when I try the following, I get a [10,5,10] array.

output = np.array[dat_list]

Thoughts?

How to Convert List of Lists to NumPy Array?

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.

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.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn 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.

How do I convert a list to an array in Python?

To convert a list to array in Python, use the np. array[] method. The np. array[] is a numpy library function that takes a list as an argument and returns an array containing all the list elements.

Is list [] and [] the same in Python?

Technically speaking, one is a function that returns an object casted to a list, and the other is the literal list object itself. Kinda like int[0] vs 0 . In practical terms there's no difference. I'd expect [] to be faster, because it does not involve a global lookup followed by a function call.

Can you convert a list to an array?

By using the toArray[] method, we can easily convert a list into an array. The toArray[] method returns an array having all the elements in the list. The returned array contains elements in the same sequence as the list.

Is [] a list or array in Python?

What Is an Array in Python? An array is also a data structure that stores a collection of items. Like lists, arrays are ordered, mutable, enclosed in square brackets, and able to store non-unique items. But when it comes to the array's ability to store different data types, the answer is not as straightforward.

Chủ Đề