Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 40 ยท Collections

Arrays and Vectors

Learn Julia arrays: 1-based indexing, push!, slicing, ranges, comprehensions, views versus copies and column-major memory order, with NumPy stand-ins.

Arrays are the workhorse of Julia. Scientific code is mostly about large blocks of numbers, so the language treats arrays as a core feature rather than a library add-on. A one-dimensional array is called a Vector, a two-dimensional one a Matrix, and both are just special cases of Array{T,N}, where T is the element type and N the number of dimensions.

This lesson covers the day-to-day skills: creating arrays, indexing from 1, growing them with push!, slicing, ranges, comprehensions, the important difference between a copy and a view, and the column-major memory layout that decides which loops are fast. Julia is read-only on this site. The runnable examples use NumPy in Python, which has very similar ideas but is different in several places, and the lesson points those places out.

Creating arrays

Square brackets with commas make a vector. Julia infers the element type from the contents.

JULIA
nums  = [10, 20, 30]          # Vector{Int64}
temps = [21.5, 19.0, 23.25]   # Vector{Float64}
mixed = [1, 2.5, 3]           # promoted to Vector{Float64}
words = ["red", "green"]      # Vector{String}
empty_ints = Int[]            # an empty Vector{Int64}
anything = Any[1, "two", :three]

typeof(nums)       # Vector{Int64} (alias for Array{Int64, 1})
eltype(temps)      # Float64
length(nums)       # 3

Helper functions create arrays of a given size:

JULIA
zeros(3)            # [0.0, 0.0, 0.0]
ones(Int, 2)        # [1, 1]
fill(7, 4)          # [7, 7, 7, 7]
rand(3)             # three random Float64 values between 0 and 1
collect(1:5)        # [1, 2, 3, 4, 5]

Typing the element type (Int[], Float64[]) matters for an empty array because Julia has nothing to infer from. Without it you would get a Vector{Any}, which is slow.

One-based indexing

Julia counts from 1, like mathematics, R, MATLAB and Fortran. The first element is v[1], and the last is v[end]. The keyword end inside brackets means "the last index of this dimension", and begin means the first.

JULIA
v = [10, 20, 30, 40, 50]

v[1]            # 10
v[end]          # 50
v[end - 1]      # 40
v[2:4]          # [20, 30, 40]
v[[1, 5]]       # [10, 50]
v[v .> 25]      # [30, 40, 50]  (boolean mask, the dot is explained in Broadcasting)

Out-of-range access is an error, not a wrap-around: v[0] and v[6] both raise a BoundsError. To write loops that work whatever the starting index of the array, loop with eachindex(v) instead of 1:length(v). Most arrays start at 1, but special array types can start elsewhere.

Reading an array

First is 1 v[1] is the first element.
Use end v[end] is always the last one.
Slices v[2:4] takes a range of positions.
1 / 2

Growing and shrinking

Vectors can change length. The mutating functions end in !, as explained in Functions.

JULIA
stack = Int[]
push!(stack, 3)             # [3]
push!(stack, 5, 8)          # [3, 5, 8]
append!(stack, [1, 2])      # [3, 5, 8, 1, 2]
pop!(stack)                 # returns 2, stack is [3, 5, 8, 1]
popfirst!(stack)            # returns 3, stack is [5, 8, 1]
pushfirst!(stack, 0)        # [0, 5, 8, 1]
insert!(stack, 2, 99)       # [0, 99, 5, 8, 1]
deleteat!(stack, 2)         # [0, 5, 8, 1]

Adding to the end is fast. Julia keeps spare capacity, so repeated push! calls are cheap on average. Matrices and higher-dimensional arrays cannot grow this way because their shape is fixed.

Ranges and comprehensions

A range such as 1:5 stores only its start, step and stop, so even 1:1_000_000_000 uses a few bytes. Turn it into a real array with collect.

JULIA
r = 1:2:9                  # 1, 3, 5, 7, 9
collect(r)                 # [1, 3, 5, 7, 9]
collect(10:-3:0)           # [10, 7, 4, 1]
range(0, 1, length = 5)    # 0.0, 0.25, 0.5, 0.75, 1.0
sum(1:100)                 # 5050

A comprehension builds an array from a loop in one expression. Add if to filter, and use two for clauses to get a matrix or all pairs.

JULIA
[x^2 for x in 1:5]                  # [1, 4, 9, 16, 25]
[x for x in 1:20 if x % 7 == 0]     # [7, 14]
[i * j for i in 1:3, j in 1:4]      # a 3x4 multiplication table
sum(x^2 for x in 1:5)               # 55 (a generator, no array is built)

With round brackets and no array, the last line is a generator: it produces values on demand, which saves memory in a big sum.

Copies and views

This is the point where Julia differs most from NumPy. A slice on the right side of an assignment makes a copy of the selected elements. Changing the copy does not touch the original.

JULIA
v = [1, 2, 3, 4, 5]
part = v[2:4]        # a new array [2, 3, 4]
part[1] = 99
v                    # still [1, 2, 3, 4, 5]

A view is a window onto the same memory. Make one with view(v, 2:4) or the macro @view v[2:4]. Writing through a view changes the parent array.

JULIA
w = @view v[2:4]
w[1] = 99
v                    # [1, 99, 3, 4, 5]

Views avoid allocating memory, which matters when you slice inside a hot loop. When a whole expression has many slices, put @views in front of it to make all of them views. The reverse side effect is aliasing. Assigning one variable to another does not copy anything: b = a makes both names refer to the same array, so you need b = copy(a) for an independent array.

JULIA
a = [1, 2, 3]
b = a            # same array
b[1] = 100
a                # [100, 2, 3]

c = copy(a)      # independent
c[1] = 0
a                # still [100, 2, 3]

In Python's NumPy the rules are the reverse for slices: a basic slice arr[1:4] is a view and you must call .copy() to get a copy. If you come from NumPy, remember that Julia's slice is a copy and the view is the opt-in.

Column-major order

A matrix is stored in memory one column after another, which is called column-major order. Fortran, MATLAB, R and Julia do this. C, Python lists and NumPy's default do the opposite (row-major).

JULIA
A = [1 2 3
     4 5 6]          # 2 rows, 3 columns
size(A)              # (2, 3)
vec(A)               # [1, 4, 2, 5, 3, 6]   <- column by column
A[2, 3]              # 6  (row 2, column 3)
A[5]                 # 3  (the fifth element in memory order)

The practical rule: in nested loops, make the first index change fastest, so the loop walks through memory in order.

JULIA
# fast: inner loop over rows (first index)
for j in axes(A, 2)
    for i in axes(A, 1)
        total += A[i, j]
    end
end

Iterating the other way around still gives the right answer but jumps through memory and can be several times slower on large arrays. Functions like sum(A) and eachindex(A) already take care of this for you.

Stand-ins you can run

NumPy shows the slicing and layout ideas well. The first example contrasts copies and views, and the second shows column-major memory order using NumPy's order="F" option. NumPy indexes from 0, so every position below is one less than the Julia position.

Python Copies, views and aliasing in NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Column-major order and loop order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Given v = [10, 20, 30, 40], what is v[end - 1] in Julia?

    end is the last index, 4, so end - 1 is 3 and the third element is 30.
  2. 2. What happens when you write part = v[2:3] and then change part[1]?

    A slice on the right-hand side copies the elements. Use @view v[2:3] if you want a window on the same memory.
  3. 3. Which loop order is fast for a Julia matrix A?

    Julia stores matrices column by column, so the first index should vary fastest in the innermost loop.
  4. 4. After a = [1, 2, 3]; b = a; b[1] = 9, what is a?

    b = a does not copy. Both names refer to the same array. Use copy(a) for an independent array.

Summary

  • Vector{T} and Matrix{T} are Array{T,N}; the element type is part of the type, so use Int[] for an empty typed vector.
  • Indexing starts at 1, end is the last index, and out-of-range access raises a BoundsError.
  • push!, pop!, append! and friends grow and shrink vectors in place.
  • Ranges are lazy; collect makes an array; comprehensions build arrays from loops with optional filters.
  • Slices copy, @view and @views share memory, and b = a only aliases; use copy for independence.
  • Matrices are stored column by column, so inner loops should run over the first index.

Next: put these arrays to work with Matrices and Linear Algebra.