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).
Slice
struct Slice
Represents a slice expression.
Objects of this type are generated when slice syntax is used within square brackets, for example:
var lst: List[Int] = [0, 1, 2, 3, 4, 5, 6, 7]
# Both produce the same new list: [6, 7].
var l1 = List(lst[6:])
var l2 = lst.__getitem__(Slice(6, len(lst)))
Fields
- start (
Optional[Int]): The starting index of the slice. - end (
Optional[Int]): The end index of the slice. - step (
Optional[Int]): The step increment value of the slice.
Implemented traits
AnyType,
Copyable,
Deinitable,
Equatable,
ImplicitlyCopyable,
Movable,
Writable
Methods
__init__
def __init__(out self, start: Int, end: Int)
Constructs a slice with the given start and end bounds.
Args:
def __init__(out self, start: Optional[Int], end: Optional[Int], step: Optional[Int], __slice_literal__: NoneType = None)
Constructs a slice with the given start, end, and step values.
Args:
- start (
Optional[Int]): The starting index of the slice. - end (
Optional[Int]): The end index of the slice. - step (
Optional[Int]): The step increment value of the slice. - slice_literal (
NoneType): Enables slice literal syntax.
__eq__
def __eq__(self, other: Self) -> Bool
Compare this slice to the other.
Args:
- other (
Self): The slice to compare to.
Returns:
Bool: True if start, end, and step values of this slice match the
corresponding values of the other slice and False otherwise.
write_to
def write_to(self, mut writer: T)
Writes the slice's string representation to a writer.
Args:
- writer (
T): The object to write to.
write_repr_to
def write_repr_to(self, mut writer: T)
Writes the slice's debug representation to a writer.
Args:
- writer (
T): The object to write to.
indices
def indices(self, length: Int) -> Tuple[Int, Int, Int]
Resolves the slice's bounds against the length of a container.
Uses the target container length to resolve negative, out-of-bounds,
or None bounds.
A negative bound counts back from the end of the container:
var s = slice(0, -1, 1)
print(s.indices(5)) # (0, 4, 1)
A None bound becomes the start or the end of the container based
on the direction of the step:
var s = slice(None, None, 1)
print(s.indices(5)) # (0, 5, 1)
An out-of-bounds bound is clamped to the nearest valid bound in the step's direction:
var s = slice(20)
print(s.indices(5)) # (0, 5, 1)
Args:
- length (
Int): The length of the container the slice applies to.
Returns:
Tuple[Int, Int, Int]: A tuple of the resolved start, end, and step.