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.
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)
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.
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)
Line 2: We declare a variable x
and initialize it with an empty vector.
Line 5: We append a single element to an empty vector x
using the function push!()
.
Line 8: We display the vector x
.
Line 11: We declare a variable y
and initialize it with an empty vector.
Line 14: We append a list of elements to an empty vector y
using the function append!()
.
Line 17: We display the vector y
.
Free Resources