Home
Search
Python List Insert ExamplesCall the insert method on list to insert an element at an index. Use a negative index to insert from the end.
Insert. In Python an element can be added anywhere in a list. With insert() we can add to the first part or somewhere in the middle of the list.
List, strings
With a positive index, we insert at an index that begins from the start of the list. So 0 is the first element. With a negative value, the index is from the list's end.
Insert example. Here we invoke the insert() method. The index 1 indicates the second element location. Lists are indexed starting at zero—they are zero-based.
Tip To insert at the first index, pass the value 0 to insert. This will create a new first element in the list.
Python program that calls insert
list = ["dot", "perls"] # Insert at index 1. list.insert(1, "net") print(list)
['dot', 'net', 'perls']
Insert, negative index. Sometimes we wish to insert based on a relative position from the end of a list. We can use a negative index for this. With -1, insert 1 from the last position.
Tip To add an element at the last position in the list, use append() not insert.
List append
Python program that uses negative insert index
ids = [1000, 1001, 1002, 1003] print(ids) # Pass a negative index to insert from the last index. # ... So -1 is the second to last position. ids.insert(-1, 0) print(ids)
[1000, 1001, 1002, 1003] [1000, 1001, 1002, 0, 1003]
A review. We invoked the insert() method on lists with a positive and negative index value. The first argument is the index we wish the new element to have.
Home
© 2007-2021 sam allen. see site info on the changelog