Python list.insert() function


The list.insert() method in Python is used to add a single element at a specific position in a list. This method allows you to specify both the index where the element should be inserted and the element itself. When an element is inserted, the elements to the right of the specified index are shifted one position to the right.

Syntax

list.insert(index, element)
  • Parameters:
    • index: The position in the list where the element should be inserted. The index is zero-based, meaning the first position is 0.
    • element: The item to be inserted into the list.

Return Value

  • The method does not return a value (None is returned implicitly).

Example Usage

  1. Inserting at the Beginning of a List:

    my_list = [2, 3, 4] my_list.insert(0, 1) # Insert 1 at index 0 print(my_list) # Output: [1, 2, 3, 4]
  2. Inserting in the Middle of a List:

    my_list = ['a', 'c', 'd'] my_list.insert(1, 'b') # Insert 'b' at index 1 print(my_list) # Output: ['a', 'b', 'c', 'd']
  3. Inserting at the End of a List: You can insert at the end of the list by specifying an index equal to the length of the list:

    my_list = [1, 2, 3] my_list.insert(len(my_list), 4) # Insert 4 at the end print(my_list) # Output: [1, 2, 3, 4]
  4. Inserting Negative Indices: Python allows negative indices, which count from the end of the list. For example, -1 refers to the last position:

    my_list = [1, 2, 3] my_list.insert(-1, 1.5) # Insert 1.5 before the last element print(my_list) # Output: [1, 2, 1.5, 3]
  5. Inserting an Element into an Empty List: If you insert an element into an empty list, that element becomes the first and only element:

    my_list = [] my_list.insert(0, 'first') # Insert 'first' at index 0 print(my_list) # Output: ['first']

Summary

  • list.insert(index, element) is a useful method for adding elements at a specific position in a list.
  • It modifies the original list in place, shifting other elements as necessary.
  • This method can be used for various purposes, such as organizing data, maintaining order, or inserting default values into a list.