Julia Tuples & NamedTuples
A tuple is a fixed-length, immutable container written with parentheses and commas. Tuples are lightweight — the compiler knows the type of every position — so Julia uses them everywhere: for multiple return values, function arguments and small records.
point = (3, 4)
person = ("Lin", 29, true)
single = (42,) # a 1-tuple needs a trailing comma
empty = ()
println(point[1], " ", person[end])
println(typeof(person))
println(length(person), " ", typeof(single), " ", length(empty))
println((42) == 42) # just parentheses, not a tuple3 true
Tuple{String, Int64, Bool}
3 Tuple{Int64} 0
true
Immutability
You can't change, add or remove elements of a tuple. To "modify" one, build a new tuple:
t = (1, 2, 3)
try
t[1] = 10
catch e
println(typeof(e))
end
t2 = (10, t[2:end]...)
println(t2)
println(Base.setindex(t, 99, 3))MethodError
(10, 2, 3)
(1, 2, 99)
Immutability isn't deep: a tuple containing an array can't swap the array for another one, but the array's own contents can still change.
Destructuring
Assigning a tuple to several names unpacks it. This is how functions "return multiple values":
function min_max_mean(v)
return minimum(v), maximum(v), sum(v) / length(v)
end
lo, hi, avg = min_max_mean([3, 9, 6])
println(lo, " ", hi, " ", avg)
a, b = (1, 2)
first_item, rest... = (10, 20, 30, 40) # slurp the remainder
println(first_item, " ", rest)
for (name, score) in [("x", 1), ("y", 2)]
print(name, "=", score, " ")
end
println()3 9 6.0
10 (20, 30, 40)
x=1 y=2
NamedTuples
A NamedTuple gives each element a name. It's like a tiny, immutable record without declaring a type:
book = (title="Dune", author="Frank Herbert", year=1965)
println(book.title)
println(book[:year], " ", book[2])
println(keys(book))
println(values(book))
println(typeof(book))
println(haskey(book, :pages))Dune
1965 Frank Herbert
(:title, :author, :year)
("Dune", "Frank Herbert", 1965)
@NamedTuple{title::String, author::String, year::Int64}
false
Because NamedTuples are immutable, you create updated copies by merging:
settings = (theme="light", size=12)
updated = merge(settings, (size=14, lang="en"))
println(updated)
x, y = 3, 4
p = (; x, y) # shorthand: names taken from the variables
println(p)
(; title, year) = (title="Up", year=2009, studio="Pixar") # property destructuring
println(title, " ", year)(theme = "light", size = 14, lang = "en")
(x = 3, y = 4)
Up 2009
Pairs
A Pair a => b is a special 2-element structure used by dictionaries and replace. Access the parts with .first and .second, or destructure it:
p = "apples" => 3
println(p.first, " ", p.second, " ", typeof(p))
k, v = p
println(k, ": ", v)
println(Dict(["a" => 1, "b" => 2])["b"])apples 3 Pair{String, Int64}
apples: 3
2
Tuples vs arrays
| Tuple | Vector | |
|---|---|---|
| Syntax | (1, "a") |
[1, 2] |
| Mutable | no | yes |
| Length | fixed, part of the type | can grow and shrink |
| Element types | each position has its own type | one element type for all |
| Best for | small fixed groups, return values, keys | data collections of any size |
Test yourself
How do you write a tuple containing just the number 5?
- (5)
- (5,)
- [5]
- tuple 5
Given nt = (a=1, b=2), which expression returns 2?
- nt.b
- nt["b"]
- nt->b
- nt(b)
What does t[1] = 0 do when t = (1, 2)?
- Changes t to (0, 2)
- Throws an error because tuples are immutable
- Returns a new tuple
- Appends 0