For example, for a 1D array with n elements, if I want to do this in Matlab I can do:
A(end+1) = 1
that assigns the value of 1 to the last element of array A which is now n+1 in length.
Is there an equivalent in Python/Numpy?
We can assign new values to an element of a NumPy array using the = operator, just like regular python lists. A few examples are below (note that this is all one code block, which means that the element assignments are carried forward from step to step).
We can add value to an array by using the append(), extend() and the insert (i,x) functions. The append() function is used when we need to add a single element at the end of the array.
You can add a NumPy array element by using the append() method of the NumPy module. The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above. The axis is an optional integer along which define how the array is going to be displayed.
If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.
You can just append a value to the end of an array/list using append
or numpy.append
:
# Python list
a = [1, 2, 3]
a.append(1)
# => [1, 2, 3, 1]
# Numpy array
import numpy as np
a = np.array([1, 2, 3])
a = np.append(a, 1)
# => [1, 2, 3, 1]
Note, as pointed out by @BrenBarn, that the numpy.append
approach creates a whole new array each time it is executed, which makes it inefficient.
I bet the Matlab/Octave operation does the same - create a new object. But I don't know if there is something like the Python id(a) to verify that.
A crude timing test in Octave supports this - creating a large array by appending is slower than stepping through the full array. Both are much slower than direct assignment like A=1:N
octave:36> t=time; N=1000000; A=[]; A(N)=1; for i=1:N A(i)=i; end; t-time
ans = -4.0374
octave:37> t=time; N=1000000; A=[]; for i=1:N A(end+1)=i; end; t-time
ans = -15.218
Extending an array with (end+1)
is more idiomatic in Javascript than Matlab.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With