Julien
Julien

Reputation: 781

Julia - Increase the size of an array, inserting a value at the beginning

I have an array filled with some values. For example, after running the following code:

array = zeros(10)

for i in 1:10
   array[i] = 2*i + 1
end

the array looks like this:

10-element Array{Float64,1}:
  3.0
  5.0
  7.0
  9.0
 11.0
 13.0
 15.0
 17.0
 19.0

Now, I would like to add a new value in the first position to obtain something like this:

11-element Array{Float64,1}:
  1.0
  3.0
  5.0
  7.0
  9.0
 11.0
 13.0
 15.0
 17.0
 19.0

How to do that?

Upvotes: 12

Views: 11344

Answers (1)

Alex Riley
Alex Riley

Reputation: 176810

It looks like you want to use pushfirst!. This function modifies your array by inserting the new value(s) at the beginning:

julia> pushfirst!(array, 1)
11-element Array{Float64,1}:
  1.0
  3.0
  5.0
  7.0
  9.0
 11.0
 13.0
 15.0
 17.0
 19.0
 21.0

(N.B. in Julia 0.6 and earlier, pushfirst! is named unshift!.)

You may also be interested in insert!, which grows the collection by inserting a value at a specific index, and push! which add one or more values to the end of the collection.

See the Deques section of the documentation for many more useful functions for modifying collections.

Upvotes: 21

Related Questions