diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index 10f72ccf9..78a604e1d 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -1265,6 +1265,10 @@ public: template void append(T &&val) const { PyList_Append(m_ptr, detail::object_or_cast(std::forward(val)).ptr()); } + template void insert(size_t index, T &&val) const { + PyList_Insert(m_ptr, static_cast(index), + detail::object_or_cast(std::forward(val)).ptr()); + } }; class args : public tuple { PYBIND11_OBJECT_DEFAULT(args, tuple, PyTuple_Check) }; diff --git a/tests/test_pytypes.cpp b/tests/test_pytypes.cpp index a8caca45c..244e1db0d 100644 --- a/tests/test_pytypes.cpp +++ b/tests/test_pytypes.cpp @@ -17,6 +17,8 @@ TEST_SUBMODULE(pytypes, m) { list.append("value"); py::print("Entry at position 0:", list[0]); list[0] = py::str("overwritten"); + list.insert(0, "inserted-0"); + list.insert(2, "inserted-2"); return list; }); m.def("print_list", [](py::list list) { diff --git a/tests/test_pytypes.py b/tests/test_pytypes.py index a0364d6af..0e8d6c33a 100644 --- a/tests/test_pytypes.py +++ b/tests/test_pytypes.py @@ -9,14 +9,16 @@ from pybind11_tests import debug_enabled def test_list(capture, doc): with capture: lst = m.get_list() - assert lst == ["overwritten"] + assert lst == ["inserted-0", "overwritten", "inserted-2"] lst.append("value2") m.print_list(lst) assert capture.unordered == """ Entry at position 0: value - list item 0: overwritten - list item 1: value2 + list item 0: inserted-0 + list item 1: overwritten + list item 2: inserted-2 + list item 3: value2 """ assert doc(m.get_list) == "get_list() -> list"