NewGuy
NewGuy

Reputation: 3423

Increment every element after inserted item in list

I have two lists that I need to keep in sync with one another. The example below is a very stripped down version of the full application.

list_1 contains data, list_2 contains index values.

list_1 = ['item1', 'item2', 'item3', 'item4']
list_2 = [0, 1, 2, 3]

Now I want to .insert() into list_1 - at any index - and keep list two in sync. That means if I insert an element at index 1 so that it looks like this:

list_1 = ['item1', 'new_item!', 'item2', 'item3', 'item4']

I know the index in this case is 1 so I can insert that at the proper point in list_2

list_2 = [0, 1, 1, 2, 3]
#            ^----- Newly inserted index

My question is, how can I efficiently update every element after this inserted value to increment by 1?


I realize this is very basic and unwarranted for this example, but for the full application, these two lists are needed and the list_2 of indexes is used to control a PyQt UI. Changing for this two list solution would be incredibly time consuming at this point.

Upvotes: 1

Views: 465

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55469

This smells like an XY problem to me, but anyway...

You can mutate list_2 like this:

list_2 = [0, 1, 2, 3]

val = 1
idx = 1

list_2.insert(idx, val)
print(list_2)

list_2[idx+1:] = [u+1 for u in list_2[idx+1:]]
print(list_2)

output

[0, 1, 1, 2, 3]
[0, 1, 2, 3, 4]

Because we use slice assignment we're mutating the original list_2 object rather than replacing it, so if any other objects have references to list_2 they will see the changes.

Upvotes: 1

Related Questions