py::builtins::list::operator []

reference operator [] (long index);                             // 1

const_reference operator [] (long index) const;                 // 2

list operator [] (std::string slice_properties);                // 3

const list operator [] (std::string slice_properties) const;    // 4
  1. Returns reference to the element at given index.

  2. Returns constant reference to the element at given index.

  3. Returns a slice of the list with given start, stop and step.

  4. Returns a constant slice of the list with given start, stop and step.

Note

Objects returned by (3) and (4) are slice and is not copyable. If copied, the copied object will copy all elements by value and will lose the special properties of slice. Use rvalues instead, i.e list<...>&& and const list<...>&&.

Parameters

index: The index of the element.

slice_properties: The properties of slice.

Format of argument slice_properties

The value of slice_properties must have the format:

"[start]:[stop][:step]"

Examples of valid slice_properties values:

"7:9" // Omitted step, automatically determined
"2::2" // Omitted stop, automatically determined
"2:3:4" // Specified everything
"::3" // Omitted both start and stop, automatically determined
":" // Omitted everything, automatically determined

Examples of invalid slice_properties values:

"" // Error: empty string
"4" // Error: string must contain a semicolor
"+-4:" // Error: invalid number
"long():" // Error: expressions not allowed, include the value

Return value

  1. Reference to the element at given index.

  2. Constant reference to the element at given index.

  3. A slice of the list with given start, stop and step.

  4. A constant slice of the list with given start, stop and step.

Complexity

  1. Constant.

  2. Constant.

Example

#include <pypp/builtins/list.hpp>
#include <pypp/builtins/print.hpp>

int main()
{
    py::list<int> list = {0, 0, 1, 3};
    py::print(list[0]);
    py::print(list["1:3"]); // Slice
}

Output:

0
{0, 1}