2.3. Tuples#

A tuple is an ordered, immutable collection of elements. We have already encountered them as the return type for functions that give back multiple values.

Like arrays, they can hold a sequence of values, but with one key difference: once a tuple is created, it cannot be changed. This property makes them useful for representing fixed collections of data.

2.3.1. Creating Tuples#

You can create a tuple by enclosing a comma-separated list of values in parentheses ().

my_tuple = (1, 3.14, "hello")
(1, 3.14, "hello")

In many contexts, such as simple assignments, the parentheses are optional.

# This creates the exact same tuple as above.
another_tuple = 1, 3.14, "hello"
(1, 3.14, "hello")

2.3.2. Accessing Elements#

You can access the elements of a tuple using indexing, just like with an array. Remember that Julia is 1-indexed.

# Access the third element.
my_tuple[3]
"hello"

You can also unpack a tuple by assigning it to a comma-separated list of variables. This is a common way to work with the results from a function that returns multiple values.

a, b, c = my_tuple

println("The value of b is: ", b)
The value of b is: 3.14

2.3.3. Tuples vs. Arrays: Key Differences#

The most important difference is mutability.

  • Arrays are mutable: You can change their size and content (e.g., using push! or my_array[i] = new_value).

  • Tuples are immutable: Once created, you cannot change a tuple in any way.

# Trying to modify a tuple will result in an error.
my_tuple[1] = 99
MethodError: no method matching setindex!(::Tuple{Int64, Float64, String}, ::Int64, ::Int64)
The function `setindex!` exists, but no method is defined for this combination of argument types.

Stacktrace:
 [1] top-level scope
   @ In[5]:2

2.3.3.1. When to Use Which?#

  • Use an Array when: Your collection of data needs to change. This is the case for most numerical work, where you might be adding results, filtering values, or modifying elements.

  • Use a Tuple when: You have a fixed collection of values that should not be modified. They are perfect for returning multiple values from a function or for situations where you want to guarantee that the data remains constant. Tuples can also be more efficient than arrays for small, fixed-size collections.