Tuesday, January 21, 2025
HomeConversionsConvert Python List to numpy Arrays

Convert Python List to numpy Arrays

To convert a Python list into a NumPy array, you can use the numpy.array() function. Here’s an example:

Example:

import numpy as np

# Python list
python_list = [1, 2, 3, 4, 5]

# Convert to NumPy array
numpy_array = np.array(python_list)

print(numpy_array)

Output:

[1 2 3 4 5]

This converts a one-dimensional Python list to a NumPy array. You can similarly convert multi-dimensional lists (like a list of lists) to multi-dimensional NumPy arrays.

See also  How can I convert the following JSON string into a Java object?

For example:

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

# Convert to 2D NumPy array
numpy_array_2d = np.array(python_list_2d)

print(numpy_array_2d)

Output:

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

Is there anything else you’d like to explore?

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x