Tilei Liu
Tilei Liu

Reputation: 155

How can i insert values based on a list of index?

this is the problem i am stumbling at. i have a list

f = [2,4,8,10,72,52,50,65,100,85,15]

list_for_loop = [3,5,8]

how could i insert a value before the index based on this list (1st index excluded)?

i am now tring this:

for index in list_for_loop:
    if index ! = list_for_loop[0]:
         f[index].insert(0)

the result is different from what i expected because every time i insert a value the list index change

hopefully i can find a way to deal with the sliding index. the ouput i expect:

f = [2,4,8,0,10,72,0,52,50,65,0,100,85,15]

Upvotes: 0

Views: 272

Answers (2)

blhsing
blhsing

Reputation: 106455

Calling list.insert in a loop unnecessarily makes the solution O(n x m) in average time complexity, where n and m are the lengths of the two input lists, since the list.insert method has to move all items after the insertion index backwards to make room for the inserted item.

You can instead create a new list by iterating through the insertion indices, extending the new list with a slice of the main list at the insertion indices, and then appending the new value to the new list after each slice, so that the average time complexity is improved to a linear O(n + m):

f = [2, 4, 8, 10, 72, 52, 50, 65, 100, 85, 15]
list_for_loop = [3, 5, 8]
new_f = []
for begin, end in zip((0, *list_for_loop), list_for_loop):
    new_f.extend(f[begin:end])
    new_f.append(0)
new_f.extend(f[end:])
print(new_f)

This outputs:

[2, 4, 8, 0, 10, 72, 0, 52, 50, 65, 0, 100, 85, 15]

Upvotes: 1

Aplet123
Aplet123

Reputation: 35512

You'd get your result by starting from the back and inserting from there:

for i in reversed(list_for_loop):
    f.insert(i, 0)

As @Barmar states, if list_for_loop isn't in increasing order, then sort it in reverse:

for i in sorted(list_for_loop, reverse=True):
    f.insert(i, 0)

Upvotes: 3

Related Questions