pic pic
Personal
Website

2f. Tuples

PhD in Economics
Code Script
This section's scripts are available here, under the name allCode.jl. They've been tested under Julia 1.11.9.

Introduction

We continue our exploration of collections, defined as objects storing multiple elements. Having previously focused on arrays, we'll now turn our attention to another form of collection known as tuples.

Tuples differ from arrays in several respects. First, they can comprise elements with heterogeneous types without incurring any performance penalty. Instead, as we'll see in Part II of the book, arrays mixing disparate types such as integers and strings perform poorly. Another key distinction is that tuples have a fixed size and are immutable. This implies that, once a tuple is created, its elements cannot be added, removed, or modified. Finally, tuples are only suitable for storing a small number of elements. In contrast, large tuples will result in slow computations at best, or directly trigger fatal errors. For this reason, why vectors remain the appropriate choice for large collections.

At this stage, we'll limit our discussion to the basic features of tuples, introducing only what's necessary to develop the fundamentals of Julia. A more in-depth exploration will follow in Part II, after we've developed the necessary tools to appreciate their role in high-performance applications.

Definition of Tuples

Tuples are defined by enclosing their elements within parentheses (), unlike the square brackets [] used in vectors. When a tuple contains more than one element, the parentheses are optional and often omitted.

Single-element tuples have stricter syntax rules, requiring parentheses () and a trailing comma , after the element. For example, a tuple with the single element 10 is represented as (10,). This notation distinguishes it from the expression (10), which would simply be interpreted as the number 10.

As with vectors, the syntax for accessing the i-th element of a tuple x is x[i].

x = (4,5,6)
x =  4,5,6           #alternative notation
Output in REPL
julia>
x
(4, 5, 6)

julia>
x[1]
4
x = (10,)    # not x = (10) (that's just x = 10)
Output in REPL
julia>
x
(10,)

julia>
x[1]
10

Tuples for Assignments

Tuples can be used to assign values to multiple variables at once. This operation is commonly referred to as unpacking or destructuring. It's implemented by placing a tuple on the left-hand side of = and a collection on the right-hand side, where the latter may be either another tuple or a vector.

(x,y) = (4,5)
 x,y  =  4,5       #alternative notation
Output in REPL
julia>
x
4

julia>
y
5
(x,y) = [4,5]
 x,y  = [4,5]      # alternative notation
Output in REPL
julia>
x
4

julia>
y
5

The technique is commonly employed when a function returns multiple values, providing convenient syntax to unpack outputs into individual variables.