📜

Understanding Python List Pop and Insert

Oct 25, 2024

Python List Functions: Pop and Insert

Overview of List Functions

  • Python lists have functions to insert or remove values.
  • Functions discussed:
    • pop: Removes and returns an element.
    • insert: Inserts a new value at a specified index.
  • Both functions permanently modify the list (destructive functions) just like append and extend.

Pop Function

  • Purpose: Removes and returns the element at the specified index.
  • Behavior:
    • If no index is specified, the last element is removed and returned.
    • After popping, the list length is reduced by one.
    • Elements to the right of the specified index shift one position to the left.
  • Usage Example:
    • Popping at index 0 removes the first element and shifts other elements left.
    • Attempting to pop at an out-of-range index results in an IndexError.

Insert Function

  • Purpose: Inserts a new value at a specified index.
  • Behavior:
    • The list length increases by one.
    • Values at and after the specified index shift one position to the right.
  • Usage Example:
    • Inserting foo at index 0 shifts existing elements to the right.
    • Inserting at the list's length is equivalent to using append.
    • If the index is larger than the list's length, the value is appended at the end.

Practical Demonstration

  • List Example: [2, 4, 6, 8, 10]
  • Creating References:
    • Both A and C point to the same list, demonstrating shared changes.
  • Pop Operations:
    • Pop without parameters removes 10 which was at the end.
    • Pop at index 0 removes 2, shifting other elements.
  • Insert Operations:
    • Insert foo at index 0 shifts existing elements to accommodate the new element.
    • Inserting bar at the end appends it without shifting other elements.
    • Inserting using an out-of-range index appends bar at the end.