Home > Net >  insert list in multilayer list in python
insert list in multilayer list in python

Time:05-09

I have a code like:

a = ['layer 1', 2, ['layer 2', 22, ['layer 3', 222]]]

and I want using insert method add the following list ['layer 4', 2222, 3333] into index 1st of layer 3rd list

what I want is:

['layer 1', 2, ['layer 2', 22, ['layer 3', ['layer 4', 2222, 3333], 222]]]

CodePudding user response:

Fairly straightforward indexing leads to this:

a = ['layer 1', 2, ['layer 2', 22, ['layer 3', 222]]]
b = ['layer 4', 2222, 3333]
a[-1][-1].insert(1, b)
print(a)

Output:

['layer 1', 2, ['layer 2', 22, ['layer 3', ['layer 4', 2222, 3333], 222]]]

CodePudding user response:

You have to insert it into the inner list. The inner list is accessed via index:

a = ['layer 1', 2, ['layer 2', 22, ['layer 3', 222]]]
b = ['layer 4', 2222, 3333]
a[2][2].insert(1, b)
  • Related