Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In place insertion into list (or array)

I'm running a script in Python, where I need to insert new numbers into an array (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])

Results in:

[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]

whereas I want:

[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
like image 990
stagermane Avatar asked May 05 '26 21:05

stagermane


1 Answers

Insert those values in backwards order. Like so:

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]

new = zip(insertion_indices, new_numbers)
new.sort(reverse=True)

for i, x in new:
    original_list.insert(i, x)

The reason this works is based on the following observation:

Inserting a value at the beginning of the list offsets the indexes of all other values by 1. Inserting a value at the end though, and the indexes remain unchanged. As a consequence, if you start by inserting the value with the largest index (10) and continue "backwards" you would not have to update any indexes.

like image 59
Ecir Hana Avatar answered May 07 '26 10:05

Ecir Hana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!