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 element
push!(empty_vector, element)
#syntax to append list of elements
append!(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 vector
x = Vector{Int64}()
#append single element
push!(x, 100)
println("Vector x after appending single element")
println(x)
#emtpy vector
y = Vector{Int64}()
#append list of elements
append!(y, [200, 300, 400, 500])
println("Vector y after appending list of elements")
println(y)

Code Explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved