May 2019
Beginner to intermediate
466 pages
10h 44m
English
We can add more elements to the end of a collection by using the push! function:
julia> arr = [1, 2, 3]
3-element Array{Int64,1}:
1
2
3
julia> push!(arr, 4)
4-element Array{Int64,1}:
1
2
3
4
julia> push!(arr, 5, 6, 7)
7-element Array{Int64,1}:
1
2
3
4
5
6
7
Note the ending exclamation mark ! for the push! function. This is a perfectly legal function name in Julia. It is a convention to warn that the function is mutating—that is, it will modify the data passed as argument to it, instead of returning a new value.
We can remove elements from the end of an array using pop!:
julia> pop!(arr)
7
julia> arr
6-element Array{Int64,1}:
1
2
3
4
5
6
The call to the pop! function has removed the last element of arr and returned it.
Read now
Unlock full access