Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

julia
communitycreator

What are tuples in Julia?

Gutha Vamsi Krishna

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.

Indices of tuples

How to declare a tuple

The code below demonstrates how to declare a tuple.

#declare and initialize a tuple
t = (1000, "hello", "educative", 30.5)

println(t)
Declaring a tuple

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-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 tuple
t = (1000, "hello", "educative", 30.5)

#accessing element at index 3
println(t[3])
Accessing an element from a tuple

If we try to alter a value in the tuple, the interpreter will throw an error:

#declare and initialize a tuple
t = (1000, "hello", "educative", 30.5)

#trying to change value from "hello" to "hi"
t[2] = "hi"
Trying to alter a value in a tuple

We get the ERROR: LoadError: MethodError: no method matching setindex! error since tuples are immutable.

RELATED TAGS

julia
communitycreator
RELATED COURSES

View all Courses

Keep Exploring