pic
Personal
Website

2f. Tuples

PhD in Economics

Introduction

We continue our exploration of collections, which are objects that store multiple elements. While the previous section focused on arrays, our focus will shift now to another form of collection known as tuples.

Tuples have a unique set of characteristics that distinguish them from arrays. On the one hand, they offer a performance advantage when working with small collections. On the other hand, they're more restrictive, due to their fixed size and immutable nature. These features entail that once a tuple is created, its elements cannot be added, removed, or modified.

Although we'll only scratch the surface of tuples at this point, a basic understanding of their concept is crucial for working with functions. We'll revisit tuples in more depth during Part II, once we've developed the necessary tools to appreciate their full relevance.

Warning!
Tuples should only be used when the number of elements is small. Large tuples will result in slow computations at best, or directly trigger fatal errors. Keep using vectors for large collections.

Defining Tuples

The i-th element of a tuple x can be accessed via x[i], similar to vectors. However, the syntax for defining them differs from vectors, and requires enclosing their elements in parentheses (), rather than square brackets [].

When tuples comprise more than one element, the use of () is optional, and their omission is in fact a common practice. On the contrary, single-element tuples have stricter syntax rules: they always require () and a trailing comma , after the element. This means that a tuple with single element 10 is represented by (10,). This contrasts with the expression (10), which would be interpreted as a number.

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) because it'd be interpreted as x = 10

Output in REPL
julia>
x
(10,)

julia>
x[1]
10

Tuples for Assignments

Tuples are particularly useful when you seek to assign values to multiple variables simultaneously. This is accomplished by using a tuple on the left-hand side of = and a collection of objects on the right-hand side. The collection to be used can be either a tuple or a vector, and the following examples demonstrate this.

(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

As we'll see, this technique is commonly employed when a function returns a collection. It allows you to unpack the returned values into multiple variables in a single statement.