list.insert()

Inserts an item at a chosen position in a list.

Returns
None
Changes the original
Yes
On this page

Example

#
Python
steps = ["HTML", "JavaScript"]
steps.insert(1, "CSS")
steps.insert(0, "Intro")
steps.insert(100, "Project")

print(steps)
Resultsaved result, you can check it
['Intro', 'HTML', 'CSS', 'JavaScript', 'Project']

Definition and usage

#

The insert(index, element) method inserts an item before the position at the given index. The remaining items shift to the right.

insert(0, x) adds an item to the start of the list. An index larger than the length of the list appends the item at the end, and a negative index counts from the end.

Inserting at the start of a large list is slow, because every item has to shift. If you often add items at both ends, use collections.deque.

Syntax

#
Syntax
list.insert(index, element)

Parameters

#
  • index

    int

    The position before which to insert the item.
  • element

    any value

    The item to insert.

Good practices

#
  • For adding to the end, use append(), it is faster and more readable.
  • When you often add items at the start, use collections.deque and its appendleft() method.

Related entries

#

Spotted a mistake or missing an example? Write to us.