Home
Map
List insert ExamplesCall the insert method on list to insert an element at an index. Use a negative index to insert from the end.
Python
This page was last reviewed on Aug 22, 2021.
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.
string List
Shows a list
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.
Shows a list
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
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.
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 22, 2021 (image).
Home
Changes
© 2007-2023 Sam Allen.