<function>
or <operator>
).
This is just notation, and the symbols <
and >
should not be misconstrued as Julia's syntax.
Action | Keyboard Shortcut |
---|---|
Previous Section | Ctrl + 🠘 |
Next Section | Ctrl + 🠚 |
List of Sections | Ctrl + z |
List of Subsections | Ctrl + x |
Close Any Popped Up Window (like this one) | Esc |
Open All Codes and Outputs in a Post | Alt + 🠙 |
Close All Codes and Outputs in a Post | Alt + 🠛 |
Unit | Acronym | Measure in Seconds |
---|---|---|
Seconds | s | 1 |
Milliseconds | ms | 10-3 |
Microseconds | μs | 10-6 |
Nanoseconds | ns | 10-9 |
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.
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
x
x[1]
x = (10,) # not x = (10) because it'd be interpreted as x = 10
x
x[1]
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
x
y
(x,y) = [4,5]
x,y = [4,5] #alternative notation
x
y
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.