Python List - Insert Method

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:

# 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:

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

Copyright 2023 © pythontic.com