Skip to main content

Mojo struct

List

The List type is a dynamically-allocated list.

It supports pushing and popping from the back resizing the underlying storage as needed. When it is deallocated, it frees its memory.

Parameters

  • T (CollectionElement): The type of the elements.
  • hint_trivial_type (Bool): A hint to the compiler that the type T is trivial. It's not mandatory, but if set, it allows some optimizations.

Fields

  • data (UnsafePointer[T, 0, 0, alignof[::AnyType,__mlir_type.!kgen.target]() if triple_is_nvidia_cuda() else 1]): The underlying storage for the list.
  • size (Int): The number of elements in the list.
  • capacity (Int): The amount of elements that can fit in the list without resizing it.

Implemented traits

AnyType, Boolable, CollectionElement, CollectionElementNew, Copyable, ExplicitlyCopyable, Movable, Sized

Methods

__init__

__init__(inout self: Self)

Constructs an empty list.

__init__(inout self: Self, *, other: Self)

Creates a deep copy of the given list.

Args:

  • other (Self): The list to copy.

__init__(inout self: Self, *, capacity: Int)

Constructs a list with the given capacity.

Args:

  • capacity (Int): The requested capacity of the list.

__init__(inout self: Self, owned *values: T)

Constructs a list from the given values.

Args:

  • *values (T): The values to populate the list with.

__init__(inout self: Self, *, owned variadic_list: VariadicListMem[elt_is_mutable, T, lifetime])

Constructs a list from the given values.

Args:

  • variadic_list (VariadicListMem[elt_is_mutable, T, lifetime]): The values to populate the list with.

__init__(inout self: Self, span: Span[is_mutable, T, lifetime])

Constructs a list from the a Span of values.

Args:

  • span (Span[is_mutable, T, lifetime]): The span of values to populate the list with.

__init__(inout self: Self, *, unsafe_pointer: UnsafePointer[T, 0, 0, alignof[::AnyType,__mlir_type.!kgen.target]() if triple_is_nvidia_cuda() else 1], size: Int, capacity: Int)

Constructs a list from a pointer, its size, and its capacity.

Args:

  • unsafe_pointer (UnsafePointer[T, 0, 0, alignof[::AnyType,__mlir_type.!kgen.target]() if triple_is_nvidia_cuda() else 1]): The pointer to the data.
  • size (Int): The number of elements in the list.
  • capacity (Int): The capacity of the list.

__copyinit__

__copyinit__(inout self: Self, existing: Self)

Creates a deepcopy of the given list.

Args:

  • existing (Self): The list to copy.

__moveinit__

__moveinit__(inout self: Self, owned existing: Self)

Move data of an existing list into a new one.

Args:

  • existing (Self): The existing list.

__del__

__del__(owned self: Self)

Destroy all elements in the list and free its memory.

__bool__

__bool__(self: Self) -> Bool

Checks whether the list has any elements or not.

Returns:

False if the list is empty, True if there is at least one element.

__getitem__

__getitem__(self: Self, span: Slice) -> Self

Gets the sequence of elements at the specified positions.

Args:

  • span (Slice): A slice that specifies positions of the new list.

Returns:

A new list containing the list at the specified span.

__getitem__(ref [self_is_lifetime] self: Self, idx: Int) -> ref [_] T

Gets the list element at the given index.

Args:

  • idx (Int): The index of the element.

Returns:

A reference to the element at the given index.

__eq__

__eq__[U: EqualityComparableCollectionElement, //](self: List[U, hint_trivial_type], other: List[U, hint_trivial_type]) -> Bool

Checks if two lists are equal.

Examples:

var x = List[Int](1, 2, 3)
var y = List[Int](1, 2, 3)
if x == y: print("x and y are equal")
var x = List[Int](1, 2, 3)
var y = List[Int](1, 2, 3)
if x == y: print("x and y are equal")

Parameters:

  • U (EqualityComparableCollectionElement): The type of the elements in the list. Must implement the traits EqualityComparable and CollectionElement.

Args:

  • other (List[U, hint_trivial_type]): The list to compare with.

Returns:

True if the lists are equal, False otherwise.

__ne__

__ne__[U: EqualityComparableCollectionElement, //](self: List[U, hint_trivial_type], other: List[U, hint_trivial_type]) -> Bool

Checks if two lists are not equal.

Examples:

var x = List[Int](1, 2, 3)
var y = List[Int](1, 2, 4)
if x != y: print("x and y are not equal")
var x = List[Int](1, 2, 3)
var y = List[Int](1, 2, 4)
if x != y: print("x and y are not equal")

Parameters:

  • U (EqualityComparableCollectionElement): The type of the elements in the list. Must implement the traits EqualityComparable and CollectionElement.

Args:

  • other (List[U, hint_trivial_type]): The list to compare with.

Returns:

True if the lists are not equal, False otherwise.

__contains__

__contains__[U: EqualityComparableCollectionElement, //](self: List[U, hint_trivial_type], value: U) -> Bool

Verify if a given value is present in the list.

var x = List[Int](1,2,3)
if 3 in x: print("x contains 3")
var x = List[Int](1,2,3)
if 3 in x: print("x contains 3")

Parameters:

  • U (EqualityComparableCollectionElement): The type of the elements in the list. Must implement the traits EqualityComparable and CollectionElement.

Args:

  • value (U): The value to find.

Returns:

True if the value is contained in the list, False otherwise.

__add__

__add__(self: Self, owned other: Self) -> Self

Concatenates self with other and returns the result as a new list.

Args:

  • other (Self): List whose elements will be combined with the elements of self.

Returns:

The newly created list.

__mul__

__mul__(self: Self, x: Int) -> Self

Multiplies the list by x and returns a new list.

Args:

  • x (Int): The multiplier number.

Returns:

The new list.

__iadd__

__iadd__(inout self: Self, owned other: Self)

Appends the elements of other into self.

Args:

  • other (Self): List whose elements will be appended to self.

__imul__

__imul__(inout self: Self, x: Int)

Multiplies the list by x in place.

Args:

  • x (Int): The multiplier number.

__iter__

__iter__(ref [self_is_lifetime] self: Self) -> _ListIter[$0, T, hint_trivial_type, $1, 1]

Iterate over elements of the list, returning immutable references.

Returns:

An iterator of immutable references to the list elements.

__reversed__

__reversed__(ref [self_is_lifetime] self: Self) -> _ListIter[$0, T, hint_trivial_type, $1, 0]

Iterate backwards over the list, returning immutable references.

Returns:

A reversed iterator of immutable references to the list elements.

__len__

__len__(self: Self) -> Int

Gets the number of elements in the list.

Returns:

The number of elements in the list.

__str__

__str__[U: RepresentableCollectionElement, //](self: List[U, hint_trivial_type]) -> String

Returns a string representation of a List.

Note that since we can't condition methods on a trait yet, the way to call this method is a bit special. Here is an example below:

var my_list = List[Int](1, 2, 3)
print(my_list.__str__())
var my_list = List[Int](1, 2, 3)
print(my_list.__str__())

When the compiler supports conditional methods, then a simple str(my_list) will be enough.

The elements' type must implement the __repr__() method for this to work.

Parameters:

  • U (RepresentableCollectionElement): The type of the elements in the list. Must implement the traits Representable and CollectionElement.

Returns:

A string representation of the list.

format_to

format_to[U: RepresentableCollectionElement, //](self: List[U, hint_trivial_type], inout writer: Formatter)

Write my_list.__str__() to a Formatter.

Parameters:

  • U (RepresentableCollectionElement): The type of the List elements. Must have the trait RepresentableCollectionElement.

Args:

  • writer (Formatter): The formatter to write to.

__repr__

__repr__[U: RepresentableCollectionElement, //](self: List[U, hint_trivial_type]) -> String

Returns a string representation of a List.

Note that since we can't condition methods on a trait yet, the way to call this method is a bit special. Here is an example below:

var my_list = List[Int](1, 2, 3)
print(my_list.__repr__())
var my_list = List[Int](1, 2, 3)
print(my_list.__repr__())

When the compiler supports conditional methods, then a simple repr(my_list) will be enough.

The elements' type must implement the __repr__() for this to work.

Parameters:

  • U (RepresentableCollectionElement): The type of the elements in the list. Must implement the traits Representable and CollectionElement.

Returns:

A string representation of the list.

append

append(inout self: Self, owned value: T)

Appends a value to this list.

Args:

  • value (T): The value to append.

insert

insert(inout self: Self, i: Int, owned value: T)

Inserts a value to the list at the given index. a.insert(len(a), value) is equivalent to a.append(value).

Args:

  • i (Int): The index for the value.
  • value (T): The value to insert.

__mul

__mul(inout self: Self, x: Int)

Appends the original elements of this list x-1 times.

var a = List[Int](1, 2)
a.__mul(2) # a = [1, 2, 1, 2]
var a = List[Int](1, 2)
a.__mul(2) # a = [1, 2, 1, 2]

Args:

  • x (Int): The multiplier number.

extend

extend(inout self: Self, owned other: List[T, hint_trivial_type])

Extends this list by consuming the elements of other.

Args:

  • other (List[T, hint_trivial_type]): List whose elements will be added in order at the end of this list.

pop

pop(inout self: Self, i: Int = -1) -> T

Pops a value from the list at the given index.

Args:

  • i (Int): The index of the value to pop.

Returns:

The popped value.

reserve

reserve(inout self: Self, new_capacity: Int)

Reserves the requested capacity.

If the current capacity is greater or equal, this is a no-op. Otherwise, the storage is reallocated and the date is moved.

Args:

  • new_capacity (Int): The new capacity.

resize

resize(inout self: Self, new_size: Int, value: T)

Resizes the list to the given new size.

If the new size is smaller than the current one, elements at the end are discarded. If the new size is larger than the current one, the list is appended with new values elements up to the requested size.

Args:

  • new_size (Int): The new size.
  • value (T): The value to use to populate new elements.

resize(inout self: Self, new_size: Int)

Resizes the list to the given new size.

With no new value provided, the new size must be smaller than or equal to the current one. Elements at the end are discarded.

Args:

  • new_size (Int): The new size.

reverse

reverse(inout self: Self)

Reverses the elements of the list.

index

index[C: EqualityComparableCollectionElement, //](ref [self_is_lifetime] self: List[C, hint_trivial_type], value: C, start: Int = 0, stop: Optional[Int] = #kgen.none) -> Int

Returns the index of the first occurrence of a value in a list restricted by the range given the start and stop bounds.

var my_list = List[Int](1, 2, 3)
print(my_list.index(2)) # prints `1`
var my_list = List[Int](1, 2, 3)
print(my_list.index(2)) # prints `1`

Parameters:

  • C (EqualityComparableCollectionElement): The type of the elements in the list. Must implement the EqualityComparableCollectionElement trait.

Args:

  • value (C): The value to search for.
  • start (Int): The starting index of the search, treated as a slice index (defaults to 0).
  • stop (Optional[Int]): The ending index of the search, treated as a slice index (defaults to None, which means the end of the list).

Returns:

The index of the first occurrence of the value in the list.

Raises:

ValueError: If the value is not found in the list.

clear

clear(inout self: Self)

Clears the elements in the list.

steal_data

steal_data(inout self: Self) -> UnsafePointer[T, 0, 0, alignof[::AnyType,__mlir_type.!kgen.target]() if triple_is_nvidia_cuda() else 1]

Take ownership of the underlying pointer from the list.

Returns:

The underlying data.

unsafe_get

unsafe_get(ref [self_is_lifetime] self: Self, idx: Int) -> ref [_] T

Get a reference to an element of self without checking index bounds.

Users should consider using __getitem__ instead of this method as it is unsafe. If an index is out of bounds, this method will not abort, it will be considered undefined behavior.

Note that there is no wraparound for negative indices, caution is advised. Using negative indices is considered undefined behavior. Never use my_list.unsafe_get(-1) to get the last element of the list. Instead, do my_list.unsafe_get(len(my_list) - 1).

Args:

  • idx (Int): The index of the element to get.

Returns:

A reference to the element at the given index.

unsafe_set

unsafe_set(inout self: Self, idx: Int, owned value: T)

Write a value to a given location without checking index bounds.

Users should consider using my_list[idx] = value instead of this method as it is unsafe. If an index is out of bounds, this method will not abort, it will be considered undefined behavior.

Note that there is no wraparound for negative indices, caution is advised. Using negative indices is considered undefined behavior. Never use my_list.unsafe_set(-1, value) to set the last element of the list. Instead, do my_list.unsafe_set(len(my_list) - 1, value).

Args:

  • idx (Int): The index of the element to set.
  • value (T): The value to set.

count

count[T: EqualityComparableCollectionElement, //](self: List[T, hint_trivial_type], value: T) -> Int

Counts the number of occurrences of a value in the list. Note that since we can't condition methods on a trait yet, the way to call this method is a bit special. Here is an example below.

var my_list = List[Int](1, 2, 3)
print(my_list.count(1))
var my_list = List[Int](1, 2, 3)
print(my_list.count(1))

When the compiler supports conditional methods, then a simple my_list.count(1) will be enough.

Parameters:

  • T (EqualityComparableCollectionElement): The type of the elements in the list. Must implement the traits EqualityComparable and CollectionElement.

Args:

  • value (T): The value to count.

Returns:

The number of occurrences of the value in the list.

swap_elements

swap_elements(inout self: Self, elt_idx_1: Int, elt_idx_2: Int)

Swaps elements at the specified indexes if they are different.

var my_list = List[Int](1, 2, 3)
my_list.swap_elements(0, 2)
print(my_list) # 3, 2, 1
var my_list = List[Int](1, 2, 3)
my_list.swap_elements(0, 2)
print(my_list) # 3, 2, 1

This is useful because swap(my_list[i], my_list[j]) cannot be supported by Mojo, because a mutable alias may be formed.

Args:

  • elt_idx_1 (Int): The index of one element.
  • elt_idx_2 (Int): The index of the other element.

unsafe_ptr

unsafe_ptr(self: Self) -> UnsafePointer[T, 0, 0, alignof[::AnyType,__mlir_type.!kgen.target]() if triple_is_nvidia_cuda() else 1]

Retrieves a pointer to the underlying memory.

Returns:

The UnsafePointer to the underlying memory.