.. index:: py::builtins::list::operator [] .. _doxycast_pypp_classpy_1_1builtins_1_1list_1a2ccb102a7b2f45d8870f79cdf6cf8017: .. _py-builtins-list-operator-subscirpt: *py::builtins::list::*\ operator [] =================================== .. code-block:: cpp 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. .. admonition:: 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 ------- .. code-block:: cpp #include #include int main() { py::list list = {0, 0, 1, 3}; py::print(list[0]); py::print(list["1:3"]); // Slice } **Output**: .. code-block:: text 0 {0, 1}