Python Forum
insert() but with negative index
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
insert() but with negative index
#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


Messages In This Thread
insert() but with negative index - by naughtysensei - Oct-01-2020, 02:06 AM
RE: insert() but with negative index - by micseydel - Oct-01-2020, 03:05 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Positive and negative numbers in a row peterp 1 1,767 Oct-29-2020, 02:42 AM
Last Post: deanhystad
  negative indices in lists Ironword 6 3,504 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