Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading