insert() but with negative index - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: insert() but with negative index (/thread-30029.html) |
insert() but with negative index - naughtysensei - Oct-01-2020 Inserting items with non-negative index gives expected results: num = [1, 2, 3] num.insert(0, "min") print(num) but with negative index, as in this case shouldn't "max" be inserted at last indexnum.insert(-1, "max") print(num) I mean its not wrong its how they made python to work but why would they do so or am being stupid here?
RE: insert() but with negative index - micseydel - Oct-01-2020 Your confusion makes sense. It took me a moment to realize it too. You're thinking that it inserts intp the index you provide. This is not quite correct. https://docs.python.org/3.8/tutorial/datastructures.html (emphasis added) Wrote:Insert an item at a given position. The first argument is the index of the element before which to insert, soGiven this, the behavior makes sense: -1 is the index of the last element, so you insert before it. |