Julia Basics

Overview

This tutorial will give some examples of basic Julia commands and syntax. It is written for students who have taken an introductory scientific programming course in Python, and highlights key differences between the two languages.

Key Differences from Python

If you are coming from Python, here are the most important differences to keep in mind as you read.

1-based indexing

Julia indexes arrays starting at 1, not 0. arr[1] is the first element. This is consistent with MATLAB, R, and Fortran, but different from Python and C.

true and false are lowercase

Python uses True and False. Julia uses true and false.

No classes — functions are the unit of abstraction

Python organizes code with classes and methods (obj.method()). Julia uses functions and multiple dispatch: you define functions that behave differently depending on the types of all their arguments. There is no self and no method-calling dot. Instead of arr.sort(), you write sort(arr).

Explicit broadcasting with .

In NumPy, np.sqrt(arr) automatically applies to every element. In Julia, you must opt in to element-wise application with a dot: sqrt.(arr). The dot is the broadcast operator and is one of the most distinctive parts of Julia syntax.

Scope rules

Variables defined inside a loop or if block in a function or script are local to that block by default. This is stricter than Python. If you define x inside a for loop, x won’t exist after the loop ends (unless you declare it with local or assign to it in an outer scope first).

using, import, and include

  • using PackageName loads a package and brings its exported names into scope (like from package import *).
  • import PackageName loads a package but requires qualification (PackageName.func()).
  • include("filename.jl") is completely different: it runs a source file as if you had typed it at the REPL. It does not create a module or namespace.

Strings concatenate with *, not +

Julia reserves + for numeric addition only. To join strings, use * or the string() function.

The Julia REPL

Julia’s interactive environment (the REPL, for Read-Eval-Print-Loop) has several modes beyond just typing code:

Mode How to enter Prompt Purpose
Julia (default) julia> Evaluate Julia expressions
Help ? help?> Look up function documentation
Package ] pkg> Add/remove/update packages
Shell ; shell> Run shell commands

For example, to break 10 into its digits:

# Type ? at the julia> prompt, then type digits(10)
digits(10)
2-element Vector{Int64}:
 0
 1

To add a package:

# Type ] at the julia> prompt, then: add Plots

To list files in the current directory:

# Type ; at the julia> prompt, then: ls

As a result, you can install packages, read documentation, and manage files without leaving Julia.

Getting Help

  • Check out the official documentation for Julia: https://docs.julialang.org/en/v1/.
  • Stack Overflow is a commonly-used resource for programming assistance.
  • At a code prompt or in the REPL, you can always type ?functionname to get help.

Comments

Comments hide statements from the interpreter or compiler. It’s a good idea to liberally comment your code so readers (including yourself!) know why your code is structured and written the way it is. Good comments focus on the why of the code logic and structure, not the what or the how. The what and how should be clear from the code itself.

Single-line comments in Julia are preceded with a #. Multi-line comments are preceded with #= and ended with =#

Suppressing Output

You can suppress output using a semi-colon (;).

4+8;

That didn’t show anything, as opposed to:

4+8
12

Suppressing output is usually unnecessary but can be useful when you are doing a multi-step calculation and don’t want to see the intermediate results or when the output of a command is extremely large.

begin...end Blocks

Sometimes you need to group multiple expressions together — for example, to suppress the output of a multi-line computation. Use a begin...end block:

x = begin
    a = 4 + 8
    b = a * 2
    a + b
end;

The block returns the value of its last expression (in this case, into x, which has a value of a + b). begin...end is the equivalent of wrapping expressions in parentheses in Python when you need multiple statements in a position that expects one.

Note that a and b will not exist outside of the begin...end block, because they are local to that block. If you want to use them later, you need to define them outside of the block.

Variables

Variables are names which correspond to some type of object. These names are bound to objects (and hence their values) using the = operator.

x = 5
5

Variables can be manipulated with standard arithmetic operators.

4 + x
9

Another advantage of Julia is the ability to use Greek letters (or other Unicode characters) as variable names. For example, type a backslash followed by the name of the Greek letter (i.e. \alpha) followed by TAB.

α = 3
3

You can also include subscripts or superscripts in variable names using \_ and \^, respectively, followed by TAB. If using a Greek letter followed by a sub- or super-script, make sure you TAB following the name of the letter before the sub- or super-script. Effectively, TAB after you finish typing the name of each \character.

β₁ = 10 # The name of this variable was entered with \beta + TAB + \_1 + TAB
10

However, try not to overwrite predefined names! For example, you might not want to use π as a variable name…

π
π = 3.1415926535897...

In the grand scheme of things, overwriting π is not a huge deal unless you want to do some trigonometry. However, there are more important predefined functions and variables that you may want to be aware of. Always check that a variable or function name is not predefined!

Data Types

Every value in Julia has a type. Types determine what operations are valid on a value and how it is stored in memory. Julia’s type system is dynamic: you don’t have to declare types for variables (unlike C), but the compiler infers them automatically. You can optionally annotate types to improve performance or enforce constraints.

This is different from Python’s duck typing: in Python, any object that has a .sort() method can be sorted. In Julia, sort() dispatches to a specific implementation based on the concrete type of the argument. This gives Julia C-like performance without C-like verbosity.

You can identify the type of a variable or expression with the typeof() function.

typeof("This is a string.")
String
typeof(x)
Int64

Numeric Types

A key distinction is between an integer type (or Int) and a floating-point number type (or float). Integers only hold whole numbers, while floating-point numbers correspond to numbers with fractional (or decimal) parts. For example, 9 is an integer, while 9.25 is a floating point number. The difference between the two has to do with the way the number is stored in memory. 9, an integer, is handled differently in memory than 9.0, which is a floating-point number, even though they’re mathematically the same value.

typeof(9)
Int64
typeof(9.25)
Float64

Sometimes certain function specifications will require you to use a Float variable instead of an Int. One way to force an Int variable to be a Float is to add a decimal point at the end of the integer.

typeof(9.0)
Float64

Strings

Strings hold characters, rather than numeric values. Even if a string contains what seems like a number, it is actually stored as the character representation of the digits. As a result, you cannot use arithmetic operators (for example) on this datum.

"5" + 5
MethodError: no method matching +(::String, ::Int64)
The function `+` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  +(::Any, ::Any, ::Any, ::Any...)
   @ Base operators.jl:596
  +(::Missing, ::Number)
   @ Base missing.jl:123
  +(::Complex{Bool}, ::Real)
   @ Base complex.jl:323
  ...

Stacktrace:
 [1] top-level scope
   @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:201

However, you can try to tell Julia to interpret a string encoding a numeric character as a numeric value using the parse() function. This can also be used to encode a numeric data as a string.

parse(Int64, "5") + 5
10

Two strings can be concatenated using *:

"Hello" * " " * "there"
"Hello there"

Ranges

A range represents a sequence of numbers without storing all of them in memory. Ranges are created with the colon operator : and are the standard way to express iteration bounds or evenly-spaced sequences.

r = 1:5           # a UnitRange: numbers 1 through 5
s = 1:0.5:3       # a StepRange: 1.0, 1.5, 2.0, 2.5, 3.0
1.0:0.5:3.0

Ranges are lazy1:1000000 takes almost no memory, just like Python’s range(1, 1000001). But unlike Python’s range, you can use Julia ranges directly in arithmetic and they work as you’d expect (broadcasting aside). To materialize a range into an array, use collect(r).

nothing, missing, and NaN

Julia distinguishes three kinds of “absent” or “invalid” values, which is important for data analysis:

Value Meaning Use case
nothing No value / void return The return value of println; a function that has nothing useful to return
missing Data is absent (from Missings.jl) A missing survey response; propagates through calculations (missing + 1missing)
NaN Not a Number (Float64) The result of 0/0; propagates differently from missingNaN + 1 is still NaN

For this course, you’ll encounter missing most often when loading real-world datasets with gaps. Use skipmissing(data) to filter out missing values, or coalesce.(data, 0.0) to replace them with a default.

Named Tuples

A NamedTuple is like a tuple where each element has a name. They are lightweight, immutable, and very useful for passing structured options to functions.

nt = (name="Alice", score=95, passed=true)
nt.name      # access by name
nt[2]        # or by position
95

Named tuples are the Julia equivalent of Python’s simple data classes or lightweight dictionaries. Many Julia functions (especially in plotting) accept named tuples for keyword-style options.

Booleans

Boolean variables (or Bools) are logical variables, that can have true or false as values. (Note: these are lowercase — Python uses True/False.)

b = true
true

Numerical comparisons, such as ==, !=, or <, return a Bool.

c = 9 > 11
false

Bools are important for logical flows, such as if-then-else blocks or certain types of loops.

Mathematical Operations

Addition, subtraction, multiplication, and division work as you would expect. Just pay attention to types! The type of the output is influenced by the type of the inputs: adding or multiplying an Int by a Float will always result in a Float, even if the Float is mathematically an integer. Division is a little special: dividing an Int by another Int will still return a float, because Julia doesn’t know ahead of time if the denominator is a factor of the numerator.

3 + 5
8
3 * 2
6
3 * 2.
6.0
6 - 2
4
9 / 3
3.0

Raising a base to an exponent uses ^, not **.

3^2
9

Julia allows the use of updating operators to simplify updating a variable in place (in other words, using x += 5 instead of x = x + 5.

Boolean Algebra

Logical operations can be used on variables of type Bool. Typical operators are && (and), || (or), and ! (not).

true && true
true
true && false
false
true || false
true
!true
false

Comparisons can be chained together.

3 < 4 || 8 == 12
true

We didn’t do this above, since Julia doesn’t require it, but it’s easier to understand these types of compound expressions if you use parentheses to signal the order of operations. This helps with debugging!

(3 < 4) || (8 == 12)
true

Data Structures

Data structures are containers which hold multiple values in a convenient fashion. Julia has several built-in data structures, and there are many extensions provided in additional packages.

Tuples

Tuples are collections of values. Julia will pay attention to the types of these values, but they can be mixed. Tuples are also immutable: their values cannot be changed once they are defined.

Tuples can be defined by just separating values with commas.

test_tuple = 4, 5, 6
(4, 5, 6)

To access a value, use square brackets and the desired index.

Julia indexing starts at 1, not 0!

test_tuple[1]
4

As mentioned above, tuples are immutable. What happens if we try to change the value of the first element of test_tuple?

test_tuple[1] = 5
MethodError: no method matching setindex!(::Tuple{Int64, Int64, Int64}, ::Int64, ::Int64)
The function `setindex!` exists, but no method is defined for this combination of argument types.
Stacktrace:
 [1] top-level scope
   @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:357

Tuples also do not have to hold the same types of values.

test_tuple_2 = 4, 5.0, 'h'
typeof(test_tuple_2)
Tuple{Int64, Float64, Char}

Tuples can also be defined by enclosing the values in parentheses.

test_tuple_3 = (4, 5.0, 'h')
typeof(test_tuple_3)
Tuple{Int64, Float64, Char}

Arrays

Arrays also hold multiple values, which can be accessed based on their index position. Arrays are commonly defined using square brackets.

test_array = [1, 4, 7, 8]
test_array[2]
4

Unlike tuples, arrays are mutable, and their contained values can be changed later.

test_array[1] = 6
test_array
4-element Vector{Int64}:
 6
 4
 7
 8

Arrays also can hold multiple types. Unlike tuples, this causes the array to no longer care about types at all.

test_array_2 = [6, 5.0, 'h']
typeof(test_array_2)
Vector{Any} (alias for Array{Any, 1})

Compare this with test_array:

typeof(test_array)
Vector{Int64} (alias for Array{Int64, 1})

Dictionaries

Instead of using integer indices based on position, dictionaries are indexed by keys. They are specified by passing key-value pairs to the Dict() method.

test_dict = Dict("A"=>1, "B"=>2)
test_dict["B"]
2

Comprehensions

Creating a data structure with more than a handful of elements can be tedious to do by hand. If your desired array follows a certain pattern, you can create structures using a comprehension. Comprehensions iterate over some other data structure (such as an array) implicitly and populate the new data structure based on the specified instructions.

[i^2 for i in 0:1:5]
6-element Vector{Int64}:
  0
  1
  4
  9
 16
 25

For dictionaries, make sure that you also specify the keys.

Dict(string(i) => i^2 for i in 0:1:5)
Dict{String, Int64} with 6 entries:
  "4" => 16
  "1" => 1
  "5" => 25
  "0" => 0
  "2" => 4
  "3" => 9

Comprehensions are powerful and are extremely useful for simple tasks. However, they can be difficult to read if they are too long or complicated, such as if multiple commands are required to populate the data structure. In these cases, it is better to use a loop. Always prioritize readability over conciseness.

map, filter, and reduce

Comprehensions are the most idiomatic way to transform collections in Julia, but you can also use map, filter, and reduce — these work similarly to Python:

map(x -> x^2, 1:5)        # like Python's map(lambda x: x**2, range(1, 6))
5-element Vector{Int64}:
  1
  4
  9
 16
 25
filter(x -> x > 3, 1:5)   # keep elements where the condition is true
2-element Vector{Int64}:
 4
 5
reduce(+, 1:5)            # sum all elements — equivalent to sum(1:5)
15

A useful pattern: mapreduce combines the two in one pass:

mapreduce(x -> x^2, +, 1:5)  # sum of squares, without creating an intermediate array
55

Functions

A function is an object which accepts a tuple of arguments and maps them to a return value. In Julia, functions are defined using the following syntax.

function my_actual_function(x, y)
    return x + y
end
my_actual_function(3, 5)
8

Functions in Julia do not require explicit use of a return statement. They will return the last expression evaluated in their definition. However, it’s good style to explicitly return function outputs. This improves readability and debugging, especially when functions can return multiple expressions based on logical control flows (if-then-else blocks).

Functions in Julia are objects, and can be treated like other objects. They can be assigned to new variables or passed as arguments to other functions.

g = my_actual_function
g(3, 5)
8
function function_of_functions(f, x, y)
    return f(x, y)
end
function_of_functions(g, 3, 5)
8

Try to structure your code using functions as often as possible to reduce bugs and simplify debugging! If you find yourself copying and pasting code, or writing the same code multiple times, consider writing a function instead. If there’s a mistake in that code, you only have to find it and fix it once.

This will also make your code more readable and easier to follow, as function names should be chosen to make it clear what that chunk of code is doing.

Short and Anonymous Functions

In addition to the long form of the function definition shown above, simple functions can be specified in more compact forms when helpful.

This is the short form:

h₁(x) = x^2 # make the subscript using \_1 + <TAB>
h₁(4)
16

This is the anonymous form:

x -> sin(x)
(x -> sin(x))(π/4)
0.7071067811865475

Mutating Functions

The convention in Julia is that functions should not modify (or mutate) their input data. The reason for this is to ensure that the data are preserved. Mutating functions are mainly appropriate for applications where performance needs to be optimized, and making a copy of the input data would be too memory-intensive.

If you do write a mutating function in Julia, the convention is to add a ! to its name, like my_mutating_function!(x). This makes it clear to anyone reading or using your code that they should expect x to be modified, rather than the output of my_mutating_function to be stored in a different variable.

Optional Arguments

There are two extremes with regard to function parameters which do not always need to be changed.

  1. The first is to hard-code them into the function body, which has a clear downside: when you do want to change them, the function needs to be edited directly.
  2. The second is to treat them as regular arguments, passing them every time the function is called. This has the downside of potentially creating bloated function calls, particularly when there is a standard default value that makes sense for most function evaluations.

Most modern languages, including Julia, allow an alternate solution, which is to make these arguments optional. This involves setting a default value, which is used unless the argument is explicitly defined in a function call.

function setting_optional_arguments(x, y, c=0.5)
    return c * (x + y)
end
setting_optional_arguments (generic function with 2 methods)

If we want to stick with the fixed value \(c=0.5\), all we have to do is call setting_optional_arguments with the x and y arguments.

setting_optional_arguments(3, 5)
4.0

Otherwise, we can pass a new value for c.

setting_optional_arguments(3, 5, 2)
16

Passing Data Structures as Arguments

Instead of passing variables individually, it may make sense to pass a data structure, such as an array or a tuple, and then unpacking within the function definition. This is straightforward in long form: access the appropriate elements using their index.

In short or anonymous form, there is a trick which allows the use of readable variables within the function definition.

h₂((x,y)) = x*y # enclose the input arguments in parentheses to tell Julia to expect and unpack a tuple
h₂ (generic function with 1 method)
h₂((2, 3)) # this works perfectly, as we passed in a tuple
6
h₂(2, 3) # this gives an error, as h₂ expects a single tuple, not two different numeric values
MethodError: no method matching h₂(::Int64, ::Int64)
The function `h₂` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  h₂(::Any)
   @ Main.Notebook ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:535

Stacktrace:
 [1] top-level scope
   @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:543
h₂([3, 10]) # this also works with arrays instead of tuples
30

Dot Syntax (Broadcasting)

Julia uses dot syntax to broadcast an operation element-wise across an array. This is the Julia equivalent of NumPy’s automatic vectorization, but it’s explicit — you add a . wherever you want element-wise behavior.

NoteWhy Broadcasting?

Julia requires you to opt-in to broadcasting because it allows you to write code that is clear and has expected behavior: if you do not want a function to be used on a array, a function that lacks broadcasting will throw an error, alerting a user that they are using the function incorrectly. This is a common source of bugs in Python (or R), where functions are often written to accept both scalars and arrays, but the behavior is not always what the user expects. And with multiple dispatch, if you want scalars and arrays to handled differently, you can use two different methods for the same function name, each with the appropriate logic.

TipPython / NumPy vs. Julia
Python (NumPy) Julia
np.sqrt(arr) sqrt.(arr)
arr * 2 arr .* 2
arr1 + arr2 arr1 .+ arr2
np.sin(arr) sin.(arr)
f(arr) where f is your function f.(arr)

The dot fuses: sin.(cos.(x)) is equivalent to a single loop and as fast as writing it by hand.

For example, to calculate the square root of 3:

sqrt(3)
1.7320508075688772

To calculate the square roots of every integer between 1 and 5:

sqrt.([1, 2, 3, 4, 5])
5-element Vector{Float64}:
 1.0
 1.4142135623730951
 1.7320508075688772
 2.0
 2.23606797749979

The same dot syntax works for arithmetic:

[1, 2, 3, 4] .* 2
4-element Vector{Int64}:
 2
 4
 6
 8

And for your own functions:

f(x) = x^2 + 1
f.([1, 2, 3])
3-element Vector{Int64}:
  2
  5
 10

You can also use the @. macro to broadcast an entire expression at once:

@. sin(cos([1, 2, 3]))  # equivalent to sin.(cos.([1, 2, 3]))
3-element Vector{Float64}:
  0.5143952585235492
 -0.4042391538522658
 -0.8360218615377305

Broadcasting is faster than writing a loop by hand (Julia fuses the operations) and is the standard way to write vectorized code. Use it liberally!

The Pipe Operator |>

Julia has a pipe operator |> that chains function calls left-to-right:

[1, 2, 3, 4, 5] |> x -> filter(iseven, x) |> sum  # sum of even numbers
6

This is equivalent to sum(filter(iseven, [1,2,3,4,5])) but avoids deeply nested parentheses. Pipelines are especially common in data-analysis workflows with DataFrames.jl.

Returning Multiple Values

You can return multiple values by separating them with a comma. This implicitly causes the function to return a tuple of values.

function return_multiple_values(x, y)
    return x + y, x * y
end
return_multiple_values(3, 5)
(8, 15)

These values can be unpacked into multiple variables.

n, ν = return_multiple_values(3, 5)
n
8
ν
15

Returning nothing

Sometimes you don’t want a function to return any values at all. For example, you might want a function that only prints a string to the console.

function print_some_string(x)
    println("x: $x")
    return nothing
end
print_some_string(42)
x: 42

Printing Text Output

The Text() function returns its argument as a plain text string. Notice how this is different from evaluating a string!

Text("I'm printing a string.")
I'm printing a string.

Text() is used in this tutorial as it returns the string passed to it. To print directly to the console, use println().

println("I'm writing a string to the console.")
I'm writing a string to the console.

Printing Variables In a String

What if we want to include the value of a variable inside of a string? We do this using string interpolation, using $variablename inside of the string.

bar = 42
Text("Now I'm printing a variable: $bar")
Now I'm printing a variable: 42

Control Flows

One of the tricky things about learning a new programming language can be getting used to the specifics of control flow syntax. These types of flows include conditional if-then-else statements or loops.

Conditional Blocks

Conditional blocks allow different pieces of code to be evaluated depending on the value of a boolean expression or variable. For example, if we wanted to compute the absolute value of a number, rather than using abs():

function our_abs(x)
    if x >= 0
        return x
    else
        return -x
    end
end
our_abs (generic function with 1 method)
our_abs(4)
4
our_abs(-4)
4

To nest conditional statements, use elseif.

function test_sign(x)
    if x > 0
        return Text("x is positive.")
    elseif x < 0
        return Text("x is negative.")
    else
        return Text("x is zero.")
    end
end
test_sign (generic function with 1 method)
test_sign(-5)
x is negative.
test_sign(0)
x is zero.

Loops

Loops allow expressions to be evaluated repeatedly until they are terminated. The two main types of loops are while loops and for loops.

While loops

while loops continue to evaluate an expression so long as a specified boolean condition is true. This is useful when you don’t know how many iterations it will take for the desired goal to be reached.

function compute_factorial(x)
    factorial = 1
    while (x > 1)
        factorial *= x
        x -= 1
    end
    return factorial
end
compute_factorial(5)
120

While loops can easily turn into infinite loops if the condition is never meaningfully updated. Be careful, and look there if your programs are getting stuck. Also, if the expression in a while loop is false when the loop is reached, the loop will never be evaluated.

For loops

for loops run for a finite number of iterations, based on some defined index variable.

function add_some_numbers(x)
    total_sum = 0 # initialize at zero since we're adding
    for i=1:x # the counter i is updated every iteration
        total_sum += i
    end
    return total_sum
end
add_some_numbers(4)
10

for loops can also iterate over explicitly passed containers, rather than iterating over an incrementally-updated index sequence. Use the in keyword when defining the loop.

function add_passed_numbers(set)
    total_sum = 0
    for i in set # this is the syntax we use when we want i to correspond to different container values
        total_sum += i
    end
    return total_sum
end
add_passed_numbers([1, 3, 5])
9

Iteration Helpers: enumerate, zip, and pairs

These functions work similarly to their Python counterparts:

# enumerate gives (index, value) pairs (but index starts at 1!)
for (i, val) in enumerate(["a", "b", "c"])
    println("Item $i is $val")
end
Item 1 is a
Item 2 is b
Item 3 is c
# zip iterates over multiple collections in lockstep
for (x, y) in zip([1, 2, 3], [4, 5, 6])
    println("$x + $y = $(x + y)")
end
1 + 4 = 5
2 + 5 = 7
3 + 6 = 9
# pairs iterates over (key, value) pairs for dictionaries
d = Dict("A"=>1, "B"=>2)
for (k, v) in pairs(d)
    println("$k: $v")
end
B: 2
A: 1

Multiple Dispatch

This is Julia’s most important concept. A generic function is a function that can have many methods, each specialized for different combinations of argument types.

# A generic function with two methods
function describe(x::Int)
    return "$x is an integer"
end

function describe(x::String)
    return "\"$x\" is a string"
end

describe(42)
describe("hello")
"\"hello\" is a string"

Julia calls this multiple dispatch because the specific method is chosen based on the types of all arguments, not just the first one (unlike Python’s single dispatch in traditional OOP).

TipType Annotations

To take advantage of multiple dispatch (and to write fast code), annotate arguments with their expected types, such as the ::Int and ::String annotations above. If you omit them, the compiler does not know what types to expect, and as a result will generate slower generic code and will not know how to choose the appropriate method.

You can also annotate return types, but this is less common.

In Python, you might write obj.method() where obj’s class determines which method runs. In Julia, you write method(obj) and the types of all arguments collectively determine the implementation. This is why Julia doesn’t need classes — dispatch replaces inheritance.

Linear Algebra

Matrices are defined in Julia as 2d arrays. Unlike basic arrays, matrices need to contain the same data type so Julia knows what operations are allowed. When defining a matrix, use semicolons to separate rows. Row elements should not be separated by commas.

test_matrix = [1 2 3; 4 5 6]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

You can also specify matrices using spaces and newlines.

test_matrix_2 = [1 2 3
                 4 5 6]
2×3 Matrix{Int64}:
 1  2  3
 4  5  6

Finally, matrices can be created using comprehensions by separating the inputs by a comma.

[i*j for i in 1:1:5, j in 1:1:5]
5×5 Matrix{Int64}:
 1   2   3   4   5
 2   4   6   8  10
 3   6   9  12  15
 4   8  12  16  20
 5  10  15  20  25

Vectors are treated as 1d matrices.

test_row_vector = [1 2 3]
1×3 Matrix{Int64}:
 1  2  3
test_col_vector = [1; 2; 3]
3-element Vector{Int64}:
 1
 2
 3

Many linear algebra operations on vectors and matrices can be loaded using the LinearAlgebra package.

Working with Files

Reading CSV files

The CSV.jl package (which needs to be installed separately into an environment; I will include this by default for assignments where file I/O is needed) reads comma-separated files into a DataFrame (this will result in an error because we don’t have the actual file):

using CSV, DataFrames
df = CSV.read("data/myfile.csv", DataFrame)
WARNING: using DataFrames.describe in module Notebook conflicts with an existing identifier.
6×3 DataFrame
Row time sensor_a sensor_b
Float64 Float64 Float64
1 0.0 12.3 45.1
2 1.0 12.5 45.0
3 2.0 12.8 44.8
4 3.0 13.0 44.5
5 4.0 13.1 44.3
6 5.0 13.3 44.0

Writing Files

# Write a DataFrame df back to CSV
CSV.write("output.csv", df)

Plain Text I/O

For plain text files, use read() (or more often, readlines()) and write():

text = read("data/myfile.txt", String)           # read entire file as a string
"Experimental run: Trial A\nDate: 2024-01-15\nTemperature: 22.5 C\nPressure: 101.3 kPa\nConcentration: 0.45 mol/L\n"
lines = readlines("data/myfile.txt")             # read as array of lines
5-element Vector{String}:
 "Experimental run: Trial A"
 "Date: 2024-01-15"
 "Temperature: 22.5 C"
 "Pressure: 101.3 kPa"
 "Concentration: 0.45 mol/L"
open("output.txt", "w") do io
    write(io, "Hello, world!")
end

DelimitedFiles (standard library)

For simple numeric matrices, use readdlm from the standard library:

using DelimitedFiles
data = readdlm("data/data.txt")   # reads into a numeric matrix
3×3 Matrix{Float64}:
 1.0  2.0  3.0
 4.0  5.0  6.0
 7.0  8.0  9.0

readdlm() will also work with other delimiters, such as tabs or spaces, by passing a second argument:

data = readdlm("data/data.txt", '\t')   # reads into a numeric matrix with tab delimiter

Error Handling

Julia’s approach to error handling is for you to try a command, and if it fails, to catch the error and handle it gracefully. This is similar to Python.

Use try/catch blocks to handle errors gracefully:

result = try
    sqrt(-1.0)
catch e
    println("Caught a ", typeof(e), ": ", e.msg)
    NaN
end
result
Caught a DomainError: sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
NaN

For more specific handling, catch particular exception types (you can e.g. explain the error in plainer language than the default error message):

try
    sqrt(-1.0)
catch e
    if e isa DomainError
        println("Cannot take sqrt of a negative real: $e")
    else
        rethrow()   # if it's another kind of error, let it propagate
    end
end
Cannot take sqrt of a negative real: DomainError(-1.0, "sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).")

Performance Tips

Julia can match C speeds, but only if you avoid a few common pitfalls. Here are the most important ones:

  1. Put performance-critical code inside functions. Code at global scope is slower because the compiler can’t assume types are stable.

  2. Avoid changing variable types. If x starts as an Int and later becomes a Float64, the compiler must generate slower generic code. This is called type instability.

  3. Pre-allocate arrays. Instead of push!-ing one element at a time, create an array of the right size with zeros(n) or Vector{Float64}(undef, n) and fill it.

You can check your code’s performance with @time:

function slow_sum(n)
    s = 0
    for i in 1:n
        s += i
    end
    return s
end
@time slow_sum(10^8)
  0.000000 seconds
5000000050000000

The first run includes compilation time (Julia compiles functions the first time they’re called). Run it twice to see the steady-state speed.

A lack of memory pre-allocation is a common source of slowdowns. Here is a concrete comparison. Both functions compute the squares of 1:n, but the first grows the array incrementally while the second allocates ahead of time:

function squares_push(n)
    result = Float64[]           # empty array
    for i in 1:n
        push!(result, i^2)       # reallocates on every append
    end
    return result
end

function squares_prealloc(n)
    result = Vector{Float64}(undef, n)  # allocate once
    for i in 1:n
        result[i] = i^2                  # write to existing slot
    end
    return result
end

@time squares_push(10^6);
@time squares_push(10^6);      # second call: steady-state speed
  0.003162 seconds (24 allocations: 17.477 MiB)
  0.009288 seconds (24 allocations: 17.477 MiB, 75.73% gc time)
@time squares_prealloc(10^6);
@time squares_prealloc(10^6);  # second call: steady-state speed
  0.001269 seconds (3 allocations: 7.641 MiB)
  0.001196 seconds (3 allocations: 7.641 MiB)

The pre-allocated version is typically 3–10× faster and allocates far less memory. The difference grows with n.

include(): Running Script Files

In Python, import file loads a module. In Julia, include("file.jl") runs a source file as if you typed its contents into the REPL. No module or namespace is created — everything defined in the file becomes available in your current scope. This is the standard way to load helper code or split a large project across multiple files.

include("myfunctions.jl")  # evaluates the file contents in the current scope
SystemError: opening file "/Users/vs498/Teaching/BEE4750/fall2026/tutorials/myfunctions.jl": No such file or directory
Stacktrace:
 [1] include(fname::String)
   @ QuartoNotebookWorker.NotebookInclude ~/.julia/packages/QuartoNotebookRunner/evCNi/src/QuartoNotebookWorker/src/NotebookInclude.jl:10
 [2] top-level scope
   @ ~/Teaching/BEE4750/fall2026/tutorials/julia-basics.qmd:1003

Package management

Sometimes you might need functionality that does not exist in base Julia. Julia handles packages using the Pkg package manager. After finding a package which has the functions that you need, you have two options:

  1. Use the package management prompt in the Julia REPL (the standard Julia interface; what you get when you type julia in your terminal). Enter this by typing ] at the standard green Julia prompt julia>. This will become a blue pkg>. You can then add new packages using add packagename.
  2. From the standard prompt, enter import Pkg; Pkg.add(packagename). The packagename package can then be used by adding using packagename to the start of the script.