In this shot, we will learn about tuples in Julia.
In Julia, tuples are similar to arrays, but there are a few differences:
()
.Similar to arrays, tuples also contain an ordered collection of items.
The code below demonstrates how to declare a tuple.
#declare and initialize a tuplet = (1000, "hello", "educative", 30.5)println(t)
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-based
index, 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.