Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 40 ยท Collections

Tuples and Named Tuples

Learn Julia tuples and named tuples: immutability, destructuring, splatting into function calls, keyword arguments from NamedTuple, with Python stand-ins.

A tuple is a small, fixed group of values. You have already used one without noticing: a function that returns a, b returns a tuple. Tuples are immutable, they can hold values of different types, and Julia remembers the type of every element, which lets the compiler generate very fast code for them. A named tuple is the same idea with a name for each slot, so you can write point.x instead of remembering that x is slot one.

This lesson covers creating tuples, reading them, destructuring (unpacking) them, splatting them into function calls, and using NamedTuple as a lightweight record. The Julia code is read-only on this site. Python has very similar tuples and namedtuple, so the runnable examples use Python and point out where Julia differs.

Creating and reading tuples

Round brackets and commas make a tuple. Indexing starts at 1, like arrays.

JULIA
t = (10, "ten", 3.5)

t[1]            # 10
t[end]          # 3.5
length(t)       # 3
typeof(t)       # Tuple{Int64, String, Float64}

single = (42,)  # a tuple with ONE element needs the trailing comma
(42)            # just the number 42 in parentheses
empty = ()      # the empty tuple

The type of a tuple lists the type of each element: Tuple{Int64, String, Float64}. That detailed type is why a tuple is not simply a Vector{Any}. The compiler knows what is in slot 2 without looking, so reading t[2] is as fast as reading a local variable. A Vector{Any} has to check the type at runtime.

Tuples are also iterable, and many array functions work on them:

JULIA
for x in (1, 2, 3)
    println(x)
end

sum((1, 2, 3))       # 6
map(x -> x * 2, (1, 2, 3))   # (2, 4, 6), a tuple again
collect((1, 2, 3))   # [1, 2, 3], now a mutable Vector

Tuple or vector?

Tuple Fixed size, immutable, typed per slot.
Vector Grows and changes, one element type.
1 / 2

Immutability

Once created, a tuple cannot be changed. Trying to assign to a slot is an error.

JULIA
t = (1, 2, 3)
t[1] = 99        # MethodError: no method matching setindex!(::Tuple{...}, ...)

To "change" a tuple you build a new one. You can also store a mutable object inside a tuple, and that object can still change; only the tuple's own slots are fixed.

JULIA
t = (1, [10, 20])
push!(t[2], 30)
t                # (1, [10, 20, 30])

Because tuples cannot be modified, they are safe to share and safe to use as dictionary keys.

JULIA
visits = Dict((3, 4) => "treasure", (0, 0) => "start")
visits[(3, 4)]   # "treasure"

Destructuring

Putting a tuple on the right side of an assignment with several names on the left unpacks it. This works for any iterable, not only tuples.

JULIA
name, age, city = ("Mira", 31, "Oslo")
name             # "Mira"

a, b = 1, 2
a, b = b, a      # swap without a temporary variable
(a, b)           # (2, 1)

first, rest... = (1, 2, 3, 4)
first            # 1
rest             # (2, 3, 4)

x, _, z = (7, 8, 9)   # underscore: ignore the middle value

Destructuring also works in function parameters of anonymous functions and in for loops, which is common when iterating over pairs or enumerate:

JULIA
for (i, letter) in enumerate(("a", "b", "c"))
    println(i, ": ", letter)
end
# 1: a
# 2: b
# 3: c

Splatting

The three dots (...) in a call spread a tuple, vector or any iterable into separate arguments. In a definition they collect the extras, as in Functions.

JULIA
args = (2, 10)
power(base, exp) = base^exp

power(args...)         # power(2, 10) = 1024
max((3, 9, 4)...)      # 9
vcat([1, 2], [3, 4], [5])   # [1, 2, 3, 4, 5]
parts = ([1, 2], [3, 4])
vcat(parts...)         # [1, 2, 3, 4]

Splatting lets you build the argument list at runtime. It is convenient but not free for very long collections, so prefer functions that take the collection directly (sum(v)) when they exist.

Named tuples

A NamedTuple gives each position a name. It is still immutable, and its type includes the names, so access by name is as fast as for a plain tuple.

JULIA
p = (x = 3, y = 4)

p.x                   # 3
p[:y]                 # 4
p[1]                  # 3 (positional access still works)
keys(p)               # (:x, :y)
values(p)             # (3, 4)
typeof(p)             # @NamedTuple{x::Int64, y::Int64}

The printed type depends on the Julia version: older versions print NamedTuple{(:x, :y), Tuple{Int64, Int64}}. Both mean the same thing. To make an updated copy, use merge:

JULIA
q = merge(p, (y = 10, z = 0))
q                     # (x = 3, y = 10, z = 0)

You can unpack by name too, using a semicolon in the pattern (Julia 1.7 and later):

JULIA
(; x, y) = p          # x = 3, y = 4

Named tuples are also the bridge between data and keyword arguments. Splatting a named tuple after a semicolon turns each field into a keyword argument.

JULIA
function draw_box(; width = 10, height = 5, border = '#')
    # ...
end

options = (width = 6, height = 3)
draw_box(; options...)        # same as draw_box(width = 6, height = 3)

Many libraries return named tuples. For example, findmax([4, 9, 2]) returns the tuple (9, 2) (value and index), and other functions return something with named fields. When you need a record with behavior, methods or mutable fields, use a struct instead.

Stand-ins you can run

Python tuples behave like Julia tuples apart from two differences: Python counts from 0, and Python's collections.namedtuple creates a class from a list of field names while Julia's named tuple is a literal value.

Python Tuples: immutability, unpacking and keys

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 second example uses namedtuple and keyword splatting. In Julia, (x = 3, y = 4) needs no class definition, and merge creates the updated copy; in Python _replace plays that role.

Python Named tuples and keyword splatting

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. How do you write a tuple with exactly one element, the number 7?

    The trailing comma makes it a tuple. (7) is just the number 7 in parentheses, and [7] is a vector.
  2. 2. What happens when you run t = (1, 2, 3); t[1] = 5?

    Tuples cannot be modified. You can build a new tuple, but you cannot assign into a slot.
  3. 3. What does power(args...) do when args = (2, 10)?

    The three dots in a call splat the collection into separate arguments.
  4. 4. Given p = (x = 3, y = 4), which expression returns 4?

    Named tuple fields are read with dot syntax or p[:y]. The other forms are not valid ways to access a field.

Summary

  • A tuple is an immutable, fixed-size group of values; its type records the type of each element.
  • Create tuples with (a, b, c); a one-element tuple needs a trailing comma.
  • Destructure with a, b = t, collect the rest with first, rest... = t, and swap with a, b = b, a.
  • Splat with f(t...) to spread a tuple into arguments.
  • NamedTuple values like (x = 3, y = 4) give fields names, are read with p.x, and are updated with merge.
  • A named tuple splatted after a semicolon becomes keyword arguments.

Next: look things up by key with Dictionaries and Sets.