How to append a NumPy array to a Python list and print the result?
NumPy: Interoperability Exercise-20 with Solution
Write a NumPy program to append a NumPy array to a Python list and print the result.
Sample Solution:
Python Code:
import numpy as np
# Create a Python list
python_list = [1, 2, 3]
print("Original Python list:",python_list)
print(type(python_list))
# Create a NumPy array
numpy_array = np.array([4, 5, 6])
print("\nOriginal NumPy list:",numpy_array)
print(type(numpy_array))
# Append the NumPy array to the Python list
# Convert the NumPy array to a list before appending
combined_list = python_list + numpy_array.tolist()
print("\nCombined list:")
# Print the resulting list
print(combined_list)
print(type(combined_list))
Output:
Original Python list: [1, 2, 3] <class 'list'> Original NumPy list: [4 5 6] <class 'numpy.ndarray'> Combined list: [1, 2, 3, 4, 5, 6] <class 'list'>
Explanation:
- Import NumPy Library: Import the NumPy library to handle arrays.
- Create Python List: Define a Python list with some example data.
- Create NumPy Array: Define a NumPy array with some example data.
- Append Array to List: Convert the NumPy array to a list using the tolist() method and append it to the Python list using the + operator.
- Print Resulting List: Output the combined list to verify the append operation.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: How to combine a NumPy array and a Pandas DataFrame into one DataFrame?
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/append-a-numpy-array-to-a-python-list-and-print-the-result.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics