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

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

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.

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

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 !

>Solution :

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

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