Julia Language Tuples Introduction to Tuples


Example

Tuples are immutable ordered collections of arbitrary distinct objects, either of the same type or of different types. Typically, tuples are constructed using the (x, y) syntax.

julia> tup = (1, 1.0, "Hello, World!")
(1,1.0,"Hello, World!")

The individual objects of a tuple can be retrieved using indexing syntax:

julia> tup[1]
1

julia> tup[2]
1.0

julia> tup[3]
"Hello, World!"

They implement the iterable interface, and can therefore be iterated over using for loops:

julia> for item in tup
           println(item)
       end
1
1.0
Hello, World!

Tuples also support a variety of generic collections functions, such as reverse or length:

julia> reverse(tup)
("Hello, World!",1.0,1)

julia> length(tup)
3

Furthermore, tuples support a variety of higher-order collections operations, including any, all, map, or broadcast:

julia> map(typeof, tup)
(Int64,Float64,String)

julia> all(x -> x < 2, (1, 2, 3))
false

julia> all(x -> x < 4, (1, 2, 3))
true

julia> any(x -> x < 2, (1, 2, 3))
true

The empty tuple can be constructed using ():

julia> ()
()

julia> isempty(ans)
true

However, to construct a tuple of one element, a trailing comma is required. This is because the parentheses (( and )) would otherwise be treated as grouping operations together instead of constructing a tuple.

julia> (1)
1

julia> (1,)
(1,)

For consistency, a trailing comma is also allowed for tuples with more than one element.

julia> (1, 2, 3,)
(1,2,3)