Convert Python list to NumPy array and print
1. List to Array Conversion
Write a NumPy program to convert a Python list to a NumPy array and print the array.
Sample Solution:
Python Code:
import numpy as np
# Initialize a Python list
python_list = [1, 2, 3, 4, 5]
print("Original array:",python_list)
print("Type:",type(python_list))
# Convert the Python list to a NumPy array
numpy_array = np.array(python_list)
print("Python list to a NumPy array:")
# Print the NumPy array
print(numpy_array)
print("Type:",type(numpy_array))
Output:
Original array: [1, 2, 3, 4, 5] Type: <class 'list'> Python list to a NumPy array: [1 2 3 4 5] Type: <class 'numpy.ndarray'>
Explanation:
- Importing numpy: We first import the numpy library for array manipulations.
- Initializing a list: A Python list is initialized with some elements.
- Converting to NumPy array: The Python list is converted to a NumPy array using np.array().
- Printing the array: The resulting NumPy array is printed.
For more Practice: Solve these Related Problems:
- Write a Numpy program to convert a deeply nested Python list into a multidimensional NumPy array with non-uniform sub-list lengths using custom padding.
- Write a Numpy program to convert a Python list containing mixed numeric types into a NumPy array and enforce a specific dtype using casting.
- Write a Numpy program to convert a Python list of lists into a NumPy array and then reshape it dynamically based on the total number of elements.
- Write a Numpy program to convert a Python list to a NumPy array and verify data integrity by comparing element-wise types.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous:NumPy Interoperability Exercise Home.
Next: Convert NumPy array to Python list and print.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.