Home  >  Article  >  Backend Development  >  How to Convert NumPy Arrays to Python Lists: tolist() vs. list()?

How to Convert NumPy Arrays to Python Lists: tolist() vs. list()?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 01:25:03856browse

How to Convert NumPy Arrays to Python Lists: tolist() vs. list()?

Conversion of NumPy Arrays into Python Lists

NumPy arrays, a powerful tool for scientific computing, are often used in situations where higher-dimensional numeric data is manipulated. However, in certain instances, converting these NumPy arrays into Python lists becomes necessary for compatibility or specific functional requirements.

Converting NumPy Arrays to Python Lists Using tolist()

The most straightforward approach to convert a NumPy array into a Python list is to utilize the tolist() method. This method creates a new Python list containing copies of the values in the array.

For example:

<code class="python">import numpy as np

array = np.array([[1, 2, 3], [4, 5, 6]])
python_list = array.tolist()

print(python_list)</code>

Output:

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

Preserving NumPy Data Types

It's important to note that the tolist() method converts NumPy values to the nearest compatible Python types. For instance, np.int32 values will be converted to Python ints. If maintaining the original NumPy data types is essential, you can use the list() function on the array. This will generate a list of NumPy scalars instead of Python values.

<code class="python">python_list = list(array)

print(python_list)</code>

Output:

[array([1, 2, 3]), array([4, 5, 6])]

Conclusion

The conversion of NumPy arrays into Python lists is a straightforward process that can be achieved using the tolist() or list() methods. Understanding the difference between these approaches and their implications for data types ensures effective usage in various scenarios.

The above is the detailed content of How to Convert NumPy Arrays to Python Lists: tolist() vs. list()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn