IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

Tuple

struct Tuple[*Ts: AnyType]

The type of a literal tuple expression.

A tuple consists of zero or more values, separated by commas.

Parameters​

  • ​*Ts (AnyType): The elements type.

Implemented traits​

AnyType, Comparable (where TypeList.all_conforms_to[Comparable]()), Copyable (where TypeList.all_conforms_to[Copyable]()), Defaultable (where TypeList.all_conforms_to[Defaultable]()), Deinitable (where TypeList.all_conforms_to[Deinitable]()), Equatable (where TypeList.all_conforms_to[Equatable]()), Hashable (where TypeList.all_conforms_to[Hashable]()), ImplicitlyCopyable (where TypeList.all_conforms_to[ImplicitlyCopyable]()), Movable (where TypeList.all_conforms_to[Movable]()), RegisterPassable (where TypeList.all_conforms_to[RegisterPassable]()), Sized, Writable (where TypeList.all_conforms_to[Writable]())

comptime members​

element_types​

comptime element_types = Ts

The elements type. Deprecated alias for Ts.

Deprecated: 'element_types' is deprecated, use 'Ts' instead

Methods​

__init__​

def __init__(out self) where TypeList.all_conforms_to[Defaultable]()

Construct a tuple with default-initialized elements.

Each element is constructed directly into the tuple's storage, so the element types do not need to be Movable.

Constraints:

All Ts must conform to Defaultable.

def __init__(out self, var *args: *Ts.values) where TypeList.all_conforms_to[Movable]()

Construct the tuple.

Constraints:

All Ts must be Movable, since each argument is moved into the tuple's storage. To construct a tuple of non-Movable elements, use the init_with initializer instead.

Args:

  • ​*args (*Ts.values): Initial values.

def __init__[F: def[idx: Int]() -> Ts.values[idx]](out self, *, init_with: F)

Construct the tuple by initializing each element in place.

The value returned by init_with[i]() is constructed directly into the tuple's storage for element i, rather than being constructed elsewhere and then moved, so the element types do not need to be Movable. Elements are initialized in index order.

Example:

struct Pinned(not Movable):
var value: Int

def __init__(out self, value: Int):
self.value = value

comptime T = Tuple[Pinned, Pinned]
var t = T(init_with=lambda [i: Int]() -> T.Ts[i]: Pinned(i * 10))
print(t[0].value, t[1].value) # 0 10

Parameters:

  • ​F (def[idx: Int]() -> Ts.values[idx]): The type of the initializer closure.

Args:

  • ​init_with (F): A function parameterized on each index in [0, len(Ts)), whose result initializes the element at that index.

def __init__(out self, *, copy: Self) where TypeList.all_conforms_to[Copyable]()

Copy construct the tuple.

Args:

  • ​copy (Self): The value to copy from.

def __init__(out self, *, deinit move: Self) where TypeList.all_conforms_to[Movable]()

Move construct the tuple.

Args:

  • ​move (Self): The value to move from.

__deinit__​

def __deinit__(deinit self) where TypeList.all_conforms_to[Deinitable]()

Destructor that destroys all of the elements.

Constraints:

All Ts must be Deinitable. When any element is not, the tuple has no implicit destructor and must be torn down with deinit_with().

__lt__​

def __lt__(self, other: Self, /) -> Bool where TypeList.all_conforms_to[Comparable]()

Compare this tuple to another tuple using less than comparison.

Args:

  • ​other (Self): The other tuple to compare against.

Returns:

Bool: True if this tuple is less than the other tuple, False otherwise.

__le__​

def __le__(self, other: Self, /) -> Bool where TypeList.all_conforms_to[Comparable]()

Compare this tuple to another tuple using less than or equal to comparison.

Args:

  • ​other (Self): The other tuple to compare against.

Returns:

Bool: True if this tuple is less than or equal to the other tuple, False otherwise.

__eq__​

def __eq__(self, other: Self) -> Bool where TypeList.all_conforms_to[Equatable]()

Compare this tuple to another tuple using equality comparison.

Args:

  • ​other (Self): The other tuple to compare against.

Returns:

Bool: True if this tuple is equal to the other tuple, False otherwise.

__gt__​

def __gt__(self, other: Self, /) -> Bool where TypeList.all_conforms_to[Comparable]()

Compare this tuple to another tuple using greater than comparison.

Args:

  • ​other (Self): The other tuple to compare against.

Returns:

Bool: True if this tuple is greater than the other tuple, False otherwise.

__ge__​

def __ge__(self, other: Self, /) -> Bool where TypeList.all_conforms_to[Comparable]()

Compare this tuple to another tuple using greater than or equal to comparison.

Args:

  • ​other (Self): The other tuple to compare against.

Returns:

Bool: True if this tuple is greater than or equal to the other tuple, False otherwise.

__contains__​

def __contains__[T: Equatable](self, value: T) -> Bool where TypeList.contains[T]()

Return whether the tuple contains the specified value.

For example:

var t = Tuple(True, 1, 2.5)
if 1 in t:
print("t contains 1")

Constraints:

T must be one of the tuple's element types. A value of any other type is never compared against the elements, so the result would always be False.

Parameters:

Args:

  • ​value (T): The value to search for.

Returns:

Bool: True if the value is in the tuple, False otherwise.

deinit_with​

def deinit_with[F: def[idx: Int](var elt: Ts.values[idx]) -> None](deinit self, deinit_func: F, /)

Consume the tuple, deinitializing each element with a closure.

Use this to tear down a Tuple whose elements are not Deinitable. Elements are visited in index order.

Parameters:

  • ​F (def[idx: Int](var elt: Ts.values[idx]) -> None): The type of the deinitializing closure.

Args:

  • ​deinit_func (F): A closure called once per element, receiving ownership of the element at that index so it can destroy it.

__len__​

static def __len__() -> Int

Return the number of elements in the tuple.

Returns:

Int: The tuple length.

def __len__(self) -> Int

Get the number of elements in the tuple.

Returns:

Int: The tuple length.

__getitem_param__​

def __getitem_param__[idx: Int](ref self) -> ref[idx] Ts.values[SIMDLength(idx)]

Get a reference to an element in the tuple.

Parameters:

  • ​idx (Int): The element to return.

Returns:

ref[idx] Ts.values[SIMDLength(idx)]: A reference to the specified element.

first_of​

def first_of[T: AnyType](ref self) -> ref[T] T

Get a reference to the first element whose type is T.

The lookup is resolved at compile time, and it is a compile-time error if the tuple has no element of type T. For example:

var t = (String("one"), 2, String("three"))
t.first_of[String]() += "!"
print(t.first_of[String]()) # one!

Parameters:

  • ​T (AnyType): The element type to look up.

Returns:

ref[T] T: A reference to the first element of type T, propagating the mutability of self.

__hash__​

def __hash__[H: Hasher](self, mut hasher: H) where TypeList.all_conforms_to[Hashable]()

Hashes the tuple using the given hasher.

Parameters:

  • ​H (Hasher): The hasher type.

Args:

  • ​hasher (H): The hasher instance.

write_to​

def write_to(self, mut writer: T) where TypeList.all_conforms_to[Writable]()

Write this tuple's text representation to a writer.

Elements are formatted using their write_to() representation. Single-element tuples include a trailing comma: (1,).

Args:

  • ​writer (T): The writer to write to.

write_repr_to​

def write_repr_to(self, mut writer: T) where TypeList.all_conforms_to[Writable]()

Write this tuple's debug representation to a writer.

Outputs the type name and parameters followed by elements formatted using their write_repr_to() representation. For example, Tuple[Int, String](Int(0), 'hello').

Args:

  • ​writer (T): The writer to write to.

reverse​

def reverse(deinit self, out result: Tuple[*#kgen.param_list.tabulate(len(Ts.values), [idx: __mlir_type.index] Ts.values[(add (mul idx, -1), len(Ts.values), -1)])]) where TypeList.all_conforms_to[Movable]()

Return a new tuple with the elements in reverse order.

Usage:

image_coords = Tuple[Int, Int](100, 200) # row-major indexing
screen_coords = image_coords.reverse() # (col, row) for x,y display
print(screen_coords[0], screen_coords[1]) # output: 200, 100

Returns:

Tuple[*#kgen.param_list.tabulate(len(Ts.values), [idx: __mlir_type.index] Ts.values[(add (mul idx, -1), len(Ts.values), -1)])]: A new tuple with the elements in reverse order.

concat​

def concat[*OtherTs: AnyType](deinit self, deinit other: Tuple[OtherTs], out result: Tuple[*#kgen.param_list.concat(Ts.values, OtherTs.values)]) where TypeList.all_conforms_to[Movable]() and TypeList.all_conforms_to[Movable]()

Return a new tuple that concatenates this tuple with another.

Usage:

var rgb = Tuple[Int, Int, Int](0xFF, 0xF0, 0x0)
var rgba = rgb.concat(Tuple[Int](0xFF)) # Adds alpha channel
print(rgba[0], rgba[1], rgba[2], rgba[3]) # 255 240 0 255

Parameters:

  • ​*OtherTs (AnyType): The types of the elements contained in the other Tuple.

Args:

Returns:

Tuple[*#kgen.param_list.concat(Ts.values, OtherTs.values)]: A new tuple with the concatenated elements.

consume_elements​

def consume_elements[F: def[idx: Int](var elt: Ts.values[idx]) -> None](deinit self, elt_handler: F, /)

Consume the tuple by transferring ownership of each element into the provided closure one at a time.

Destructuring assignment such as a, b = t^ desugars to reference-returning subscripts, so it copies each element and cannot extract elements whose type is Movable but not ImplicitlyCopyable. consume_elements hands each element to elt_handler by value instead, so a tuple of move-only elements can still be taken apart. Elements are visited in index order.

Example:

List is Movable but not ImplicitlyCopyable, so its elements can be moved out of a tuple but not copied out:

# Each `List` is moved out of the tuple, one at a time.
var t = ([1, 2, 3], [4, 5, 6])

def handler[idx: Int](var elt: t.Ts[idx]):
print(len(elt)) # prints 3, then 3

t^.consume_elements(handler)

Parameters:

  • ​F (def[idx: Int](var elt: Ts.values[idx]) -> None): The type of the element handler closure.

Args:

  • ​elt_handler (F): A function called once for each element of the tuple, receiving ownership of the element at that index.