How to append to an empty vector in Julia
In Julia, vectors are one-dimensional arrays that can be resized, which means we can add or remove elements. A vector stores an ordered collection of elements and can hold duplicate elements as well.
We can append elements to an empty vector in Julia using the below functions:
push!(): This function is used to append one element to a vector.append!(): This function is used to append a list of elements to a vector.
Syntax
Let's view the syntax below.
#syntax to append single elementpush!(empty_vector, element)#syntax to append list of elementsappend!(empty_vector, list_of_elements)
Parameters
The push!() function takes the following parameters:
vector: We pass this as the first parameter.element: We pass this to append as the second parameter.
The append!() function takes the following parameters:
vector: We pass this as the first parameter.list_of_elements: We pass this to append as a second parameter.
Code Example
Let's take a look at an example of this.
#emtpy vectorx = Vector{Int64}()#append single elementpush!(x, 100)println("Vector x after appending single element")println(x)#emtpy vectory = Vector{Int64}()#append list of elementsappend!(y, [200, 300, 400, 500])println("Vector y after appending list of elements")println(y)
Code Explanation
Line 2: We declare a variable
xand initialize it with an empty vector.Line 5: We append a single element to an empty vector
xusing the functionpush!().Line 8: We display the vector
x.Line 11: We declare a variable
yand initialize it with an empty vector.Line 14: We append a list of elements to an empty vector
yusing the functionappend!().Line 17: We display the vector
y.
Free Resources