What are tuples in Julia?
Overview
In this shot, we will learn about tuples in Julia.
In Julia, tuples are similar to arrays, but there are a few differences:
- Tuples are immutable; this means that we cannot alter the values of a tuple once they are assigned.
- Tuples track the type of each element. This means that they store the type of each value present in a tuple.
- Tuples are declared as comma-separated-values between parentheses
().
Similar to arrays, tuples also contain an ordered collection of items.
How to declare a tuple
The code below demonstrates how to declare a tuple.
#declare and initialize a tuplet = (1000, "hello", "educative", 30.5)println(t)
How to access an element of a tuple
We provide the index of an element between square brackets [] to access that element.
tuple[index_of_the_element]
Note: Tuples also follow a
1-basedindex, just like arrays in Julia.
Let’s look at an example of how to access an element of a tuple in Julia.
In the following example, we want to access an element educative, which has an index of 3 in tuple t:
#declare and initialize a tuplet = (1000, "hello", "educative", 30.5)#accessing element at index 3println(t[3])
If we try to alter a value in the tuple, the interpreter will throw an error:
#declare and initialize a tuplet = (1000, "hello", "educative", 30.5)#trying to change value from "hello" to "hi"t[2] = "hi"
We get the ERROR: LoadError: MethodError: no method matching setindex! error since tuples are immutable.