w3resource

How to append a NumPy array to a Python list and print the result?


20. Array Append to List Conversion

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.

For more Practice: Solve these Related Problems:

  • Write a Numpy program to append a NumPy array to a Python list and then flatten the combined structure into a single list.
  • Write a Numpy program to convert a NumPy array to a list, append another list of elements, and then convert back to an array verifying the new shape.
  • Write a Numpy program to append a multidimensional NumPy array to a Python list and then use list comprehensions to extract specific subarrays.
  • Write a Numpy program to merge a Python list with a NumPy array by appending and then performing a vectorized operation on the combined data.

Go to:


Previous: How to combine a NumPy array and a Pandas DataFrame into one DataFrame?
Next: NumPy I/O operations Exercises Home

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.