John
John

Reputation: 73

Duplicating and Inserting into Nested List Python

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.

Upvotes: 3

Views: 84

Answers (1)

vks
vks

Reputation: 67968

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']

Upvotes: 2

Related Questions