3

I currently have nested list:

A = [[a1, a2, a3], c1, [a4, a5, a6], c2]

I also have another list:

B = [b1, b2]

I wish to duplicate A by the number of elements in B and then insert list B in the following way:

AB = [[a1, a2, a3], b1, c1, [a4, a5, a6], b1, c2, [a1, a2, a3], b2, c1, [a4, a5, a6], b2, c2]

The duplication I have managed to figure out easily:

AB = A * len(B)

However, the inserting of a list into a nested list has me completely stumped.

I'm currently using Python 3.6.1 and the size of list A and B can change but are always in the format of:

A template = [[x1, x2, x3], z1 ...]
B template = [y1, ...]

Any assistance will be greatly appreciated.

1 Answer 1

2

You can do it in a simple manner.

A = [['a1', 'a2', 'a3'], 'c1', ['a4', 'a5', 'a6'], 'c2']

AB=[]

B = ['b1', 'b2']
for i in B:
    for j in A:
        if isinstance(j,list):
            AB.append(j)
        else:
            AB.append(i)
            AB.append(j)
print AB

Output:[['a1', 'a2', 'a3'], 'b1', 'c1', ['a4', 'a5', 'a6'], 'b1', 'c2', ['a1', 'a2', 'a3'], 'b2', 'c1', ['a4', 'a5', 'a6'], 'b2', 'c2']

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, been thinking for hours and you showed me the simplest way for a Python beginner.

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.