🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Array Operations

Array operations add, remove, and join values in an existing array. Names that end with ! change the array they are given.

push! adds and pop! removes at the end

push! grows the array by one value. pop! takes the last value off and gives it back.

a = [1, 2]
push!(a, 3)
println(a)
println(pop!(a))
println(a)

append! and vcat join arrays end to end

append! adds all of a second array into the first one. vcat builds a new array from the two it is given.

a = [1, 2]
append!(a, [3, 4])
println(a)
println(vcat([5], [6, 7]))

insert! and deleteat! work at an index

insert! places a value at index 2 and shifts the rest right. deleteat! then removes index 1, and in checks what remains.

a = [10, 30]
insert!(a, 2, 20)
println(a)
deleteat!(a, 1)
println(a)
println(20 in a)
println(99 in a)

Example

cart = ["pen"]
push!(cart, "book")
append!(cart, ["bag"])
println(cart)
println(pop!(cart))
println("pen" in cart)
println(cart)

Key points

  • push!: push!(a, 4) adds one value at the end of a.
  • pop!: pop!(a) removes the last value and gives it back.
  • append!: append!(a, [4, 5]) adds every value of a second array at the end.
  • insert!: insert!(a, 2, 9) places a value at an index and shifts the rest right.
  • deleteat!: deleteat!(a, 2) removes the value at an index.
  • Joining: vcat(a, b) builds a new array from two arrays placed end to end.
  • Membership: 3 in a is true when the value 3 is in a.

In this example, cart starts with one item, push! adds "book", and append! adds "bag" from a one-item array. The pop! call removes and prints "bag", the in check confirms "pen" is still in the cart, and the last print shows the two remaining items.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does pop!([1, 2, 3]) give, and what is left in the array?