Julia Tuples
A tuple is a fixed collection of values grouped in parentheses. Once a tuple is created, its values cannot be changed.
A tuple groups values in parentheses
The tuple holds a number and a string together. Indexes read the values back one at a time.
t = (1, "one")
println(t)
println(t[1])
println(t[2])A named tuple reads fields by name
Each value in a named tuple carries a name. A dot followed by the name reads that field.
t = (name = "Ana", age = 31)
println(t)
println(t.name)
println(t.age)Several return values arrive as a tuple
A function can return several values with one return line. The caller receives them together as a tuple.
function splitnum(n)
return div(n, 10), n % 10
end
pair = splitnum(47)
println(pair)
println(pair[1])
println(pair[2])Example
function lowhigh(x, y)
return min(x, y), max(x, y)
end
result = lowhigh(9, 4)
println(result)
println(result[1])
person = (name = "Bo", age = 28)
println(person.name)
println(person.age)Key points
- Tuple literal: values in parentheses, separated by commas, like (1, "one").
- Indexing: t[1] gives the first value and t[2] gives the second value.
- Fixed: a tuple cannot be changed after it is created.
- Named tuple: (name = "Ana", age = 31) gives each value a name.
- Field access: t.name reads the value stored under the name name.
- Return values: a function can return several values at once, and they arrive as a tuple.
In this example, lowhigh returns the smaller and larger of its two inputs as one tuple, so result is (4, 9) and result[1] is 4. The named tuple person then shows field access, printing the name Bo and the age 28.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
For t = (name = "Ana", age = 31), what does t.age give?