Python Forum
insert() but with negative index
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
insert() but with negative index
#1
Inserting items with non-negative index gives expected results:
num = [1, 2, 3]
num.insert(0, "min")
print(num)
Output:
['min', 1, 2, 3]
but with negative index, as in this case shouldn't "max" be inserted at last index
num.insert(-1, "max")
print(num)
Output:
['min', 1, 2, 'max', 3]
I mean its not wrong its how they made python to work but why would they do so or am being stupid here?
Reply
#2
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/dat...tures.html (emphasis added) Wrote:Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Given this, the behavior makes sense: -1 is the index of the last element, so you insert before it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Positive and negative numbers in a row peterp 1 1,755 Oct-29-2020, 02:42 AM
Last Post: deanhystad
  negative indices in lists Ironword 6 3,432 Jan-08-2020, 01:00 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020