Tuples

Intermediate Julia

Anthony Markham

Quantitative Developer

Tuples - introduction

  • An immutable, ordered collection of values.
  • Can contain values of any data type.
  • Integer indexing, just as with vectors.
Intermediate Julia

Tuples - why?

Advantages

  • Your code is safer if you use tuples for data that you want to protect.
  • Faster than vectors, using less memory.

Disadvantages

  • Unable to sort tuples.
  • Unable to append, delete, or change values.
Intermediate Julia

Tuples - syntax

  • Define a tuple using parentheses, with a comma between each value.
my_tuple = (10, 20, 30, 40)
  • A tuple can contain multiple data types.
my_mixed_tuple = (10, "Hello", 30, true)
Intermediate Julia

Tuples - indexing

  • Tuples are indexed using integers (the same as vectors).
my_tuple = (10, 20, 30, 40)
println(my_tuple[1])
10
println(my_tuple[2:3])
(20, 30)
Intermediate Julia

Tuples - immutability

  • We can not add or remove values to a tuple after it has been created.
  • We can not modify values contained within a tuple.
my_tuple = (10, 20, 30, 40, 50)
append!(my_tuple, 60)
MethodError: no method matching append!(::NTuple{5, Int64}, ::Int64)
my_tuple = (10, 20, 30, 40, 50)
my_tuple[1] = 15
MethodError: no method matching setindex!(::NTuple{5, Int64}, ::Int64, ::Int64)
Intermediate Julia

Tuples - immutability

  • A tuple will track the number of elements it contains, as this can not change.
  • This is reflected in the type of the variable.
my_vector = [10, 20, 30, 40, 50]
my_tuple = (10, 20, 30, 40, 50)

println(typeof(my_vector))
println(typeof(my_tuple))
Vector{Int64}
NTuple{5, Int64}
Intermediate Julia

Tuples - NamedTuple

  • A NamedTuple is a tuple with elements that can also be accessed by a name assigned to the value.
  • Each value in a NamedTuple is represented by a unique name.
  • NamedTuples have the same immutability properties as tuples.
my_named_tuple = (name="Anthony", country="Australia", city="Sydney")
println(my_named_tuple[1])
println(my_named_tuple.name)
Anthony
Anthony
Intermediate Julia

Let's practice!

Intermediate Julia

Preparing Video For Download...