Python List - insert method

The insert method adds an element into a python list before the specified index.

List Updated 11 Sep 2016 1 min read

Method Name

insert

Method Signature

insert(indexBefore, newElement)

Method Overview

  • The insert method adds a new element to the list.
  • The new element is added to the list before the specified index.

Parameters

indexBefore - The index before which the new element is to be added.

newElement - The new element that is to be added to the list.

Return Value

None

Example

python
# Example Python program that creates a list and inserts elements to it

# Create a list

            langs = ["COBOL", "Pascal"];

# Insert an element at the beginning of the list

            langs.insert(0, "Fortran");

# Insert an element at the end of the list

            langs.insert(len(langs), "Python");

# Insert an element at the end of the list

            langs.insert(len(langs), "Java");

# Insert an element at a specified index

            langs.insert(3, "C++");

print(langs);

Output

Output
['Fortran', 'COBOL', 'Pascal', 'C++', 'Python', 'Java']