Question

Say I have a nested list such as:

a = [[4,5,7],[3,5,7],[5,8,0]]

I want to insert the inner list z=[0,0,0] into specific locations within the list a. The locations are determined by a list call index.

So if the index list is:

index = [2,4,5]

The result would be z inserted into a at locations 2,4 and 5. The resultant list would be:

a_insert = [[[4,5,7],[3,5,7],[0,0,0],[5,8,0],[0,0,0],[0,0,0]]

                                2               4       5  
                                ^               ^       ^

Where the list [0,0,0] is now inserted at the locations specified by the list index.

A naive attempt is,

for ind in index:
    c = a.insert(ind,z)

which does not work. Can anyone suggest a solution?

No correct solution

OTHER TIPS

Your given code seems to work just fine here.

In [1]: a = [[4,5,7],[3,5,7],[5,8,0]]
In [2]: z = [0,0,0]
In [3]: index = [2,4,5]
In [4]: for ind in index:
   ...:     a.insert(ind, z)
In [5]: a
Out[5]: [[4, 5, 7], [3, 5, 7], [0, 0, 0], [5, 8, 0], [0, 0, 0], [0, 0, 0]]

I noticed that your last line attempts to insert into the list b. Could this be a typo, since you referred to the list a previously?

Edit

Your updated code snippet in the original post is now:

for ind in index:
    c = a.insert(ind,z)

c will always be None after such an operation. z will, however, be inserted into a in the manner that your post describes, and a's contents will be updated in-place.

This is because insert directly modifies the given list, and does not return any value (other than None).

Perhaps you wanted to keep the original list a as it was, and create a new list, c, with the values inserted? In that case, a simple solution would be as follows:

c = a[:] # Create a shallow copy of a
for ind in index:
    c.insert(ind, z)

# a is now [[4, 5, 7], [3, 5, 7], [5, 8, 0]]
# c is now [[4, 5, 7], [3, 5, 7], [0, 0, 0], [5, 8, 0], [0, 0, 0], [0, 0, 0]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top