Skip to content
AgileLogics
6 min read

Arrays

Prerequisites: for loops and ranges

An array is an ordered, growable collection. A one-dimensional array is called a Vector:

scores = [90, 72, 85]
println(scores)
println(typeof(scores))
println(scores[1], " ", scores[end], " ", length(scores))

push!(scores, 64)
pushfirst!(scores, 100)
println(scores)

last_score = pop!(scores)
println(last_score, " ", scores)

scores[2] = 95
println(scores[2:3])
println(85 in scores)
[90, 72, 85]
Vector{Int64}
90 85 3
[100, 90, 72, 85, 64]
64 [100, 90, 72, 85]
[95, 72]
true
  • Indexes start at 1; end is the last index.
  • push! adds to the end, pushfirst! to the front, pop! removes and returns the last element.
  • a[2:3] is a slice — a new array with those elements.
  • x in a checks membership.

The ! convention

Functions whose names end in ! modify their argument. Their counterparts without ! return a new value and leave the original alone:

nums = [3, 1, 2]
sorted = sort(nums)
println(nums, " ", sorted)
sort!(nums)
println(nums)
[3, 1, 2] [1, 2, 3]
[1, 2, 3]

Element types

An array knows the type of its elements:

println(typeof([1, 2.5]))
println(typeof(["a", 1]))
words = String[]
push!(words, "hi")
println(words, " ", eltype(words))
println(zeros(3), " ", ones(Int, 2), " ", fill("x", 3))
Vector{Float64}
Vector{Any}
["hi"] String
[0.0, 0.0, 0.0] [1, 1] ["x", "x", "x"]
  • Mixing numbers promotes them ([1, 2.5] is a Vector{Float64}).
  • String[] creates an empty vector of strings; Int[] of integers.
  • zeros, ones, and fill create arrays of a given size.
  • Arrays with a concrete element type like Vector{Float64} are fast; Vector{Any} works but is slower.

Arrays are shared, not copied

a = [1, 2, 3]
b = a
b[1] = 99
println(a)
c = copy(a)
c[1] = 0
println(a, " ", c)
[99, 2, 3]
[99, 2, 3] [0, 2, 3]

Assignment gives the same array a second name. Use copy when you need an independent one.

Common mistakes

  • Using a[0] — that's an error; the first element is a[1].
  • Forgetting that b = a doesn't copy.
  • Trying push! on a range: push!(1:3, 4) fails because ranges are read-only. collect it first.