<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, 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.
The defining characteristic of tuples is their fixed size and immutability. This implies that, once a tuple is created, its elements cannot be added, removed, or modified. While these restrictions might initially seem limiting, they also bring substantial performance gains when working with small collections.
At this point, we'll only touch on the basics. A more in-depth exploration of tuples will follow in Part II, after we've developed the necessary tools to understand the role of tuples in high-performance scenarios.
The syntax for accessing the i-th element of a tuple x
is x[i]
, similar to vectors. Likewise, defining tuples requires enclosing their elements in parentheses ()
, which contrasts with the square brackets []
used in vectors.
When tuples comprise more than one element, the use of ()
is optional and its omission is in fact a common practice. On the contrary, single-element tuples have stricter syntax rules: you must use parentheses ()
and a trailing comma ,
after the element. For example, a tuple with the single element 10
is represented as (10,)
. This notation differentiates a tuple from the expression (10)
, which would be interpreted simply as the number 10.
x = (4,5,6)
x = 4,5,6 #alternative notation
x
x[1]
x = (10,) # not x = (10) (it'd be interpreted as x = 10)
x
x[1]
Tuples are particularly useful for simultaneously assigning values to multiple variables. This is achieved by placing a tuple on the left-hand side of =
and a collection on the right-hand side (either another tuple or a vector). The following examples demonstrate both options.
(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 later, this technique is commonly employed when a function returns multiple values, enabling you to unpack the returned values into individual variables.