pythonlistmutable

Python List NOT modifying in place while splicing?


I have a list of chars. I want to insert a string in between the chars at given index. For that I wrote a function to insert the item (string) in the list in-place. The list inside the function is correct BUT it is NOT modifying the original list that I am passing. I believe Python List is mutable.

def insert_inplace(lst, idx, item_to_insert):
    lst = lst[:idx] + lst[idx+1:]
            
    lst[:idx] = lst[:idx]
    lst[idx+1:] = lst[idx:]
    lst[idx] = item_to_insert
    print(lst) 
    # getting correct answer here

string_list = ["a", "b", "c", "d", "e"]
replacement = "new inserted item"
i = 2
insert_inplace(string_list, i, replacement)
# string_list is not getting modified

Solution

  • you're reassigning the lst variable within the function. Reassigning lst to a new list breaks the connection between the original list

    def insert_inplace(lst, idx, item_to_insert):
        lst[idx:idx] = [item_to_insert]  # Insert item_to_insert at index idx
        print(lst)  # Print the modified list inside the function
    
    string_list = ["a", "b", "c", "d", "e"]
    replacement = "new inserted item"
    i = 2
    insert_inplace(string_list, i, replacement)
    # string_list should now be modified
    print(string_list)
    

    Output

    ['a', 'b', 'new inserted item', 'c', 'd', 'e']
    

    More Simpler Approach

    def insert_inplace(lst, idx, item_to_insert):
        lst.insert(idx, item_to_insert)
    
    string_list = ["a", "b", "c", "d", "e"]
    replacement = "new inserted item"
    i = 2
    insert_inplace(string_list, i, replacement)
    print(string_list)
    

    Yeilds same

    ['a', 'b', 'new inserted item', 'c', 'd', 'e']
    

    time complexity is o(n)