Skip to main content
Log in

Mojo struct

List

struct List[T: CollectionElement, hint_trivial_type: Bool = False]

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]): 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, UnknownDestructibility

Methods

__init__

__init__(out self)

Constructs an empty list.

__init__(out self, *, other: Self)

Creates a deep copy of the given list.

Args:

  • other (Self): The list to copy.

__init__(out self, *, capacity: Int)

Constructs a list with the given capacity.

Args:

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

@implicit __init__(out self, owned *values: T)

Constructs a list from the given values.

Args:

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

__init__(out self, *, owned elements: VariadicListMem[T, origin])

Constructs a list from the given values.

Args:

  • elements (VariadicListMem[T, origin]): The values to populate the list with.

@implicit __init__(out self, span: Span[T, origin])

Constructs a list from the a Span of values.

Args:

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

__init__(out self, *, ptr: UnsafePointer[T], length: Int, capacity: Int)

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

Args:

  • ptr (UnsafePointer[T]): The pointer to the data.
  • length (Int): The number of elements in the list.
  • capacity (Int): The capacity of the list.

__copyinit__

__copyinit__(out self, existing: Self)

Creates a deepcopy of the given list.

Args:

  • existing (Self): The list to copy.

__moveinit__

__moveinit__(out self, owned existing: Self)

Move data of an existing list into a new one.

Args:

  • existing (Self): The existing list.

__del__

__del__(owned self)

Destroy all elements in the list and free its memory.

__bool__

__bool__(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, 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, idx: Int) -> ref [self] 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, 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, 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__(mut self, owned other: Self)

Appends the elements of other into self.

Args:

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

__imul__

__imul__(mut self, x: Int)

Multiplies the list by x in place.

Args:

  • x (Int): The multiplier number.

__iter__

__iter__(ref self) -> _ListIter[T, hint_trivial_type, self_is_origin]

Iterate over elements of the list, returning immutable references.

Returns:

An iterator of immutable references to the list elements.

__reversed__

__reversed__(ref self) -> _ListIter[T, hint_trivial_type, self_is_origin, False]

Iterate backwards over the list, returning immutable references.

Returns:

A reversed iterator of immutable references to the list elements.

__len__

__len__(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.

write_to

write_to[W: Writer, U: RepresentableCollectionElement, //](self: List[U, hint_trivial_type], mut writer: W)

Write my_list.__str__() to a Writer.

Parameters:

  • W (Writer): A type conforming to the Writable trait.
  • U (RepresentableCollectionElement): The type of the List elements. Must have the trait RepresentableCollectionElement.

Args:

  • writer (W): The object 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.

bytecount

bytecount(self) -> Int

Gets the bytecount of the List.

Returns:

The bytecount of the List.

append

append(mut self, owned value: T)

Appends a value to this list.

Args:

  • value (T): The value to append.

insert

insert(mut 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(mut 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(mut 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(mut 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(mut 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(mut 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(mut 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(mut self)

Reverses the elements of the list.

index

index[C: EqualityComparableCollectionElement, //](ref self: List[C, hint_trivial_type], value: C, start: Int = 0, stop: Optional[Int] = Optional(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(mut self)

Clears the elements in the list.

steal_data

steal_data(mut self) -> UnsafePointer[T]

Take ownership of the underlying pointer from the list.

Returns:

The underlying data.

unsafe_get

unsafe_get(ref self, idx: Int) -> ref [self] 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(mut 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(mut 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(ref self) -> UnsafePointer[T, mut=self_is_mut, origin=self_is_origin]

Retrieves a pointer to the underlying memory.

Returns:

The pointer to the underlying memory.