w3resource

NumPy: Append values to the end of an array

NumPy: Array Object Exercise-12 with Solution

Write a NumPy program to append values to the end of an array.

Python NumPy: Append values to the end of an array

Sample Solution:-

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a Python list
x = [10, 20, 30]

# Printing a message indicating the original array
print("Original array:")

# Printing the original array
print(x)

# Appending values to the end of the array using np.append() and assigning the result back to 'x'
x = np.append(x, [[40, 50, 60], [70, 80, 90]])

# Printing a message indicating the array after appending values
print("After append values to the end of the array:")

# Printing the array after appending values
print(x)

Sample Output:

Original array:                                                         
[10, 20, 30]                                                            
After append values to the end of the array:                            
[10 20 30 40 50 60 70 80 90]

Explanation:

In the above code -

x = [10, 20, 30]: Defines a list called ‘x’ with three integer elements.

x = np.append(x, [[40, 50, 60], [70, 80, 90]]): The np.append() function is used to append two lists of three elements each to the original list ‘x’. The resulting object is converted into a NumPy array and stored back into ‘x’.

Python-Numpy Code Editor:

Previous: Write a NumPy program to convert a list and tuple into arrays.
Next: Write a NumPy program to create an empty and a full array.

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.