Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 40 ยท Practice and Review

Julia Cheat Sheet

A one-page Julia cheat sheet: syntax, collections, strings, types, multiple dispatch, broadcasting, performance rules and Pkg commands with short examples.

This is the quick-reference page for the whole Julia track. It lists the syntax and functions you reach for every day, grouped by topic, with a one-line comment for each. Every snippet is read-only because Julia is not installed on this site; the two runnable stand-ins at the end show the NumPy equivalents of the array idioms.

Each section links to the lesson with the full explanation. Bookmark it, and use it with the REPL open: type ?name at the help?> prompt for the official docs of any function listed here.

Remember these five

Indexing from 1 v[1] is first, v[end] is last.
Dispatch Methods chosen by all arguments.
Dots f.(x) applies f to every element.
1 / 2

Basics

JULIA
x = 5                       # variable (type is inferred)
const RATE = 0.07           # constant global
println("x = $x, double = $(2x)")   # interpolation
# comment       #= block comment =#
typeof(x)                   # Int64
x isa Integer               # true

Numbers: Int64 and Float64 by default, 1//3 is a Rational, 2 + 3im is Complex, big(2)^100 is a BigInt. Operators: + - * / ^, integer division รท (div), remainder % (rem) and mod. / always returns a float: 4 / 2 == 2.0. Details in Numbers and Math.

Need Write
Equal / not equal ==, != (or โ‰ )
Identical object ===
And / or / not &&, `
Approximately equal a โ‰ˆ b, isapprox(a, b)
Largest / smallest Int typemax(Int), typemin(Int)
Parse and convert parse(Int, "42"), Float64(3), string(42)

Control flow

JULIA
if x > 0
    "positive"
elseif x == 0
    "zero"
else
    "negative"
end

x > 0 ? "pos" : "non-pos"           # ternary
x > 0 && println("positive")        # short-circuit

for i in 1:3 println(i) end         # ranges include both ends
for (i, v) in enumerate(["a", "b"]) println(i, v) end
while x > 0
    x -= 1
    x == 2 && break                 # break / continue
end

See Control Flow. Blocks end with end; indentation is not significant.

Functions

JULIA
square(x) = x^2                              # short form
function area(w, h = 1; scale = 1.0)         # optional + keyword
    return w * h * scale
end
area(2, 3; scale = 0.5)                      # 3.0
(x, y) -> x + y                              # anonymous
map(x -> x^2, 1:3)                           # [1, 4, 9]
sort!(v)                                     # ! means "mutates its argument"
f(args...)                                   # varargs / splatting
a, b = divrem(17, 5)                         # multiple return values

More in Functions. Pipe with x |> f, compose with f โˆ˜ g.

Collections

JULIA
v = [1, 2, 3]            # Vector{Int64}
push!(v, 4); pop!(v)     # append / remove last
v[2:3]; v[end]; v[[1, 3]]
A = [1 2; 3 4]           # 2x2 Matrix; spaces = columns, ; = rows
A[1, 2]; A[:, 1]; size(A); length(A)
zeros(2, 3); ones(3); rand(2, 2); reshape(1:6, 2, 3)
[x^2 for x in 1:5 if isodd(x)]       # comprehension
@view v[2:3]             # no-copy slice
Task Julia
Sum / product / extremes sum(v), prod(v), maximum(v), minimum(v)
Sort / reverse sort(v), sort(v; rev = true), reverse(v)
Search findfirst(==(3), v), findall(>(2), v), 3 in v
Transform map(f, v), filter(iseven, v), reduce(+, v)
Tests any(>(2), v), all(>(0), v), count(iseven, v)
Combine zip(a, b), enumerate(v), vcat(a, b), hcat(a, b)

Tuples ((1, "a")) are immutable, named tuples are (x = 1, y = 2). Dictionaries and sets:

JULIA
d = Dict("a" => 1, "b" => 2)
d["c"] = 3
get(d, "z", 0)                 # 0 when the key is missing
haskey(d, "a")                 # true
for (k, v) in d println(k, v) end
keys(d); values(d)

s = Set([1, 2, 3])
union(s, Set([3, 4])); intersect(s, Set([2, 9])); setdiff(s, Set([1]))

See Arrays and Vectors, Tuples and Named Tuples and Dictionaries and Sets.

Strings

JULIA
s = "Hello, Julia"
length(s); uppercase(s); lowercase(s)
"ab" * "cd"                  # concatenation uses *
"ab"^3                       # "ababab"
split("a,b,c", ",")          # ["a", "b", "c"]
join(["a", "b"], "-")        # "a-b"
replace(s, "Julia" => "world")
occursin("Jul", s); startswith(s, "He"); endswith(s, "ia")
'a'                          # a Char; "a" is a String
r"\d+"                       # regex literal

Indexes are byte positions; see Strings and Characters.

Types and structs

JULIA
abstract type Shape end                    # cannot be instantiated

struct Circle <: Shape                     # immutable
    r::Float64
end

mutable struct Counter                     # fields can change
    n::Int
end

struct Pair2{T}                            # parametric
    a::T
    b::T
end

Base.@kwdef struct Config                  # keyword constructor with defaults
    host::String = "localhost"
    port::Int = 8080
end
Config(port = 9000)

Useful reflection: typeof(x), supertype(T), subtypes(T), fieldnames(T), isa, T <: S. See The Type System and Structs and Custom Types.

Multiple dispatch

JULIA
area(c::Circle) = pi * c.r^2
area(r::Rect)   = r.w * r.h
collide(a::Ship, b::Rock) = "damage"       # depends on both arguments
Base.:+(a::Vec, b::Vec) = Vec(a.x + b.x, a.y + b.y)   # extend Base for your type
Base.show(io::IO, v::Vec) = print(io, "(", v.x, ", ", v.y, ")")
methods(area)                              # list all methods
@which area(Circle(1))                     # which method runs

Generic code: function f(x::T) where {T<:Real}. Iteration protocol: define Base.iterate and Base.length. See Multiple Dispatch, Parametric Types and Generic Code and Interfaces and Iteration Protocols.

Broadcasting and linear algebra

JULIA
sqrt.([1, 4, 9])               # [1.0, 2.0, 3.0]
v .+ 1;  v .* w;  v .^ 2       # element-wise
@. y = 2x + sin(x)             # every call in the expression is dotted and fused
A * B                          # matrix product
A .* B                         # element-wise product
A'                             # transpose (adjoint)
using LinearAlgebra
det(A); inv(A); eigen(A); I(3)
A \ b                          # solve A x = b

See Broadcasting and the Dot Syntax and Matrices and Linear Algebra.

Performance rules

Rule Why
Put work in functions, not global scope Lets the compiler specialize on types
Keep functions type stable zero(x), eltype(A) instead of literals of a fixed type
Annotate struct fields with concrete or parametric types Known memory layout
Loop with the first index innermost Column-major storage
Preallocate and mutate (f!, .=, mul!) Fewer allocations
Use @views for slices you only read No copies
Add @inbounds only after testing Skips bounds checks
Benchmark with @btime f($x) using BenchmarkTools
Inspect with @code_warntype f(x) Shows unstable types

See Performance Tips and How Julia Compiles Code.

Errors, files and tests

JULIA
try
    parse(Int, "abc")
catch e
    println("failed: ", e)
finally
    println("done")
end
throw(ArgumentError("bad value"))
@assert x > 0 "x must be positive"

open("data.txt", "w") do io
    println(io, "hello")
end
readlines("data.txt"); read("data.txt", String)

using Test
@testset "area" begin
    @test area(Rect(2, 3)) == 6
    @test area(Circle(1)) โ‰ˆ pi
    @test_throws MethodError area("x")
end

Concurrency and metaprogramming

JULIA
Threads.nthreads()                           # start with: julia -t 4
Threads.@threads for i in 1:100 ... end      # parallel loop
t = Threads.@spawn heavy(x); fetch(t)        # task and result
ch = Channel{Int}(8); put!(ch, 1); take!(ch)
a = Threads.Atomic{Int}(0); Threads.atomic_add!(a, 1)

quote x + 1 end                              # an expression (Expr)
macro twice(e) :($e; $e) end                 # a tiny macro
@time f(x); @elapsed f(x); @macroexpand @time f(x)

See Threads, Tasks and Distributed Computing and Macros and Metaprogramming.

Packages and the REPL

REPL mode Press Prompt
Normal (default) julia>
Help ? help?>
Shell ; shell>
Package manager ] (@v1.x) pkg>
JULIA
# in package mode (press ])
activate .                 # use ./Project.toml
add DataFrames Plots       # install packages
status                     # list direct dependencies
update                     # update within compat bounds
remove Plots
instantiate                # install what Manifest.toml says
test                       # run test/runtests.jl
generate MyPkg             # new package skeleton

In code: using Pkg; Pkg.add("DataFrames"). Tooling around it: Revise.jl (live reloading), include("file.jl"), julia --project script.jl, julia -t auto. See Packages and Environments.

NumPy equivalents you can run

If you come from Python, these two stand-ins show the NumPy form of the idioms in this sheet. The comment on each line is the Julia counterpart.

Python Array idioms 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.

The biggest differences: NumPy counts from 0 and its end-exclusive slices, while Julia counts from 1 with inclusive ranges, and NumPy defaults to row-major memory where Julia uses column-major.

The second stand-in covers collections: Python's dict, set and comprehension forms next to Julia's.

Python Dictionaries, sets and comprehensions

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.

Note the dictionary order: Python keeps insertion order, while a Julia Dict does not promise any order; use OrderedDict from OrderedCollections.jl if you need one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you write the last element of v?

    end inside square brackets means the last index. Negative indexes are not supported.
  2. 2. Which line multiplies two matrices element by element?

    * is the matrix product; the dotted version broadcasts the multiplication over matching elements.
  3. 3. How do you join strings?

    Julia uses * for concatenation and ^ for repetition. + is reserved for numbers.
  4. 4. Which command installs the exact versions recorded in Manifest.toml?

    instantiate downloads whatever the active project and manifest list, which reproduces the environment.

Summary

  • Indexing starts at 1, ranges are inclusive, end is the last index, and * joins strings.
  • Functions have methods; dispatch uses every argument, and you can extend Base functions for your own types.
  • Dots broadcast and fuse; plain operators on matrices are the real linear-algebra ones.
  • Fast code is inside functions, type stable, column-major, preallocated and measured with BenchmarkTools.
  • ] opens the package manager; one environment per project with Project.toml and Manifest.toml.

Go back to the start any time with What Is Julia?, or revisit your weak spots in Practice Exercises with Solutions.