Insert an element to each list in a list at given indices

Question:

I’ve been struggling with something for quite a long time so I thought I would ask my question here.
I have a list of lists that looks like this : list = [[2,3,4,5,2,3],[3,4,1,6,9,9]]
Inside, there is, as you can see, two lists that have the same number of elements.
I also have what i call an "index list" that looks like this : index = [0,2,4]
What I’ve been trying to do is essentially to put a specific number inside each list of my list of lists at each given index of my index list.

For example, in my case, my goal is to put insert a 1 in my list in each of my 2 lists at the index 0, 2 and 4 (because my index list = [0,2,4]).

To be more clear, the ouput I would like to get is this :
[[1,2,3,1,4,5,1,2,3],[1,3,4,1,1,6,1,9,9]]
Each 1 is inserted in each list of my list of lists at the index 0,2,4 of each lists.

But I’ve been really struggling to achieve that : I found an answer that works for a simple list but I can’t make it work for a list of multiple lists.

I would appreciate it a lot if someone could help me ! Thanks a lot !

Asked By: Rod3291

||

Answers:

Try this:

arrays = [[2,3,4,5,2,3],[3,4,1,6,9,9]]

indexes = [0,2,4]

for i in range(len(arrays)):
    for j in range(len(indexes)):
        k = indexes[j] + j
        arrays[i] = arrays[i][:k] + [1] + arrays[i][k:]

print(arrays)
Answered By: bbbbbbbbb

Try:

t = [[2,3,4,5,2,3],[3,4,1,6,9,9]]
indices = [0,2,4]
k = 1
offset = 0
for i in indices:
        for ele in t:
                ele.insert(i+offset,k)
        offset+=1
print(t)

we maintain an offset variable and increment it by 1 to accomodate for the shift in indices every time we insert

Answered By: Fares_Hassen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.