NumPy: Append values to the end of an array
Append Values to Array
Write a NumPy program to 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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics