0

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?

1
  • c will always be bound to None, since insert mutates the list in-place and does not return anything. Commented Mar 3, 2014 at 17:53

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was a typo - fixed now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.